DEV Community

loading...

Simple .npmrc management

Christian
I am an agile enthusiast, clean code connoisseur & testing aficionado
Originally published at cri.dev ・1 min read

Originally posted on cri.dev

One way to provide environment variables when running a script with npm, is to create a file called .npmrc in the root of the project (same level as package.json).

Here is an example .npmrc (note: lowercase):

telegram_token=abc
telegram_chat_id=123
Enter fullscreen mode Exit fullscreen mode

git ignore this file, especially in public repos

I find it useful to have an npm script called node, which runs node, but by loading the .npmrc file:

In your package.json

  "scripts": {
    "node": "node",
    ...
Enter fullscreen mode Exit fullscreen mode

Then, in your Node.js script, you would read the environment variables with the npm_config_ prefix.

You can run this now with npm run node -- index.js

The index.js file:

console.log(process.env.npm_config_telegram_token)
> abc
console.log(process.env.npm_config_telegram_chat_id)
> 123
Enter fullscreen mode Exit fullscreen mode

Here is how I personally manage my environments in Node.js.

Example

Below you can find an example using the library simple-telegram-message:

const { sendMessageFor } = require('simple-telegram-message')
const sendMessage = sendMessageFor(process.env.npm_config_telegram_token, process.env.npm_config_telegram_chat_id)
sendMessage(`Hi from bot!`)
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
ayoubmehd profile image
Ayoub

Thanks, that is very useful

Collapse
christianfei profile image
Christian Author

Glad it was helpful!