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

前端 未结 30 1212

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

提交回复
热议问题