How to use . env in NPM publications?

Asked

Viewed 649 times

1

I’m trying to publish a npm package with a file .env using the package dotenv.

When I test locally using the process.env.MINHA_PROPRIEDADE, it works normally though, when I try to use installing the package published globally, it doesn’t work.

I have tried to change the content of .gitignore not to include . env, but this did not solve the problem.

Is it possible for me to use an environment variable when publishing a package on NPM? If so, where am I missing?

The code I’m using is as follows::

require('dotenv').config()
function main() {
  console.log(`A chave é ${process.env.MINHA_VARIAVEL}`)
}

main()

And my file .env has the following:

MINHA_VARIAVEL=TESTE

Basically, this is a package to test how to do this...

What happens when I run locally is the printing on the console of the phrase "The key is TEST", whereas when I publish and install globally, the return I get is "The key is Undefined".

  • 2

    You have the code example to clarify what you are doing?

  • @Virgilionovic I edited with an example code

  • 1

    It won’t be that your program is trying to access . env from another location when it publishes, because in this case the package is installed in the modules. I’m just guessing, not stating ;)

  • 1

    @Guilhermenascimento was just that, I had to change the config and add the parameter {path: path.resolve(__dirname, '.env')} to solve the problem. Put this as an answer for me to accept (:

1 answer

2


Probably the path location that lib will look for when installed on npm_modules will be different from when testing the direct script, so to solve this use the path.:

Getting something like (like himself Felipe Avelar discovered):

{ path: path.resolve(__dirname, '.env'), ... }

In the example it was combined to __dirname (https://nodejs.org/docs/latest/api/globals.html#globals_dirname), but depending could use the process.cwd()

In the case of process.cwd() this will take the path from where the script is executed and not the path from where it is, ie if it is a global script and you run in a different folder it will be able to read the envs of various folders (which is at the moment), but this depends on the need.

  • In this case, the problem was that the dotenv sought, precisely, in the process.cwd(), but . env, being installed globally, needed me to access the point where the script file was executed, so I used the __dirname and operated locally, due to the fact that __dirname be equal to process.cwd() when executed locally. (:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.