How do I setup the dotenv file in Node.js?

前端 未结 30 1137

I am trying to use the dotenv NPM package and it is not working for me. I have a file config/config.js with the following content:



        
相关标签:
30条回答
  • 2020-12-07 14:37

    On some operating sytems (mostly some linux distros, I am looking at you raspbian), .env files don't work. rename them and import that

    0 讨论(0)
  • 2020-12-07 14:38

    I solved this using:

    require('dotenv').config({path: __dirname + '/.env'})
    

    or with an absolute path:

    C:\\asd\\auhsd\\.env
    

    If it does not find the .env file, it will return undefined.

    0 讨论(0)
  • 2020-12-07 14:39

    Take care that you also execute your Node script from the ROOT folder.

    E.g. I was using a testing script in a subfolder called ./bin/test.js. Calling it like: node ./bin/test.js worked totally fine. Calling it from the subfolder like:

    $ pwd
    ./bin
    $ node ./test.js
    

    causes dotenv to not find my ./.env file.

    0 讨论(0)
  • 2020-12-07 14:39

    The '.env' file should be in the root directory of your node js server file (server.js or for me).

    If you placed the '.env' file at the root of your project, it won't work. My mistake was that I have the server.js file nested in a folder named 'controller'.

    So I had to fix it by placing the .env file in the same directory as the server.js file.

    0 讨论(0)
  • 2020-12-07 14:40

    Working Solution:

    If you are using webpack (which you definitely should), use a very handy plugin dotenv-webpack which solves the issue of reading environment variables from .env file

    Make sure .env is in root directory of your project.

    Steps to install the plugin:

    1. npm i -D dotenv-webpack
    2. In webpack.config file:
         const Dotenv = require('dotenv-webpack');
         module.exports = {
              ...
              plugins: [
                    new Dotenv(),
                    ...
              ],
              ...
         };
    

    Now you can call any environment variable defined in .env file using process.env in any js file

    0 讨论(0)
  • 2020-12-07 14:40

    I had to literally use no name for the .env file, just have the .env extension and save the file like that and it worked.

    0 讨论(0)
提交回复
热议问题