Setting Environment Variables for Node to retrieve

前端 未结 16 2110
-上瘾入骨i
-上瘾入骨i 2020-11-22 15:41

I\'m trying to follow a tutorial and it says:

There are a few ways to load credentials.

  1. Loaded from environment variables,
16条回答
  •  不知归路
    2020-11-22 16:26

    Make your life easier with dotenv-webpack. Simply install it npm install dotenv-webpack --save-dev, then create an .env file in your application's root (remember to add this to .gitignore before you git push). Open this file, and set some environmental variables there, like for example:

    ENV_VAR_1=1234
    ENV_VAR_2=abcd
    ENV_VAR_3=1234abcd
    

    Now, in your webpack config add:

    const Dotenv = require('dotenv-webpack');
    const webpackConfig = {
      node: { global: true, fs: 'empty' }, // Fix: "Uncaught ReferenceError: global is not defined", and "Can't resolve 'fs'".
      output: {
        libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
      },
      plugins: [new Dotenv()]
    };
    module.exports = webpackConfig; // Export all custom Webpack configs.
    

    Only const Dotenv = require('dotenv-webpack');, plugins: [new Dotenv()], and of course module.exports = webpackConfig; // Export all custom Webpack configs. are required. However, in some scenarios you might get some errors. For these you have the solution as well implying how you can fix certain error.

    Now, wherever you want you can simply use process.env.ENV_VAR_1, process.env.ENV_VAR_2, process.env.ENV_VAR_3 in your application.

提交回复
热议问题