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.