DEV Community 👩‍💻👨‍💻


Posted on • Originally published at

Simple .npmrc management

Originally posted on

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):

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:

> abc
> 123
Enter fullscreen mode Exit fullscreen mode

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


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

Top comments (2)

ayoubmehd profile image

Thanks, that is very useful

christianfei profile image
Christian Author

Glad it was helpful!

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.