I try to access env vars from webpack.config.js through process.env.env_name, although i've access to env vars in my .env (locally) through process.env.env_name in webpack.config.js, i can't access env vars declared in config/default.js file. any idea? –
            Asked
            
        
        
            Active
            
        
            Viewed 9,055 times
        
    2 Answers
5
            
            
        You can use webpack.DefinePlugin like this
plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('development'),
                'BASE_URL': JSON.stringify('http://localhost:5000/')
            }
        })
    ],
Then read in your js code like this
 process.env.BASE_URL
 
    
    
        Tony Ngo
        
- 19,166
- 4
- 38
- 60
4
            
            
        Option 1 - Variables on webpack file
You can pass in your env variables on the script:
webpack --env.MY_VARIABLE=VALUE --env.MY_OTHER_VARIABLE=OTHER_VALUE
and access it:
...
module.exports = env => {
  // Use env.<YOUR VARIABLE> here:
  console.log('MY_VARIABLE: ', env.MY_VARIABLE); // 'VALUE'
  ...
};
Option 2 - Variables on your app
Or you can read it from your env file using some package, like dotenv.
run npm i dotenv.
Import it on your webpack.config.js file:
// if .env is on same folder as webpack.config.js
var dotenv = require('dotenv')
// if is located elsewhere
var dotenv = require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' });
// same as above, but with abstraction
var dotenv = require('dotenv').config({path: __dirname + '/.env'});
And finally:
// define a new plugin on your webpack
plugins: [
    ...
    new webpack.DefinePlugin({
        // try:
        "process.env": dotenv.parsed
        // or:
        'process.env': JSON.stringify(dotenv.config().parsed)
    }),
]
Now you can read your variables inside your app as process.env.MY_VARIABLE, defined in .env.
 
    
    
        pedrobern
        
- 1,134
- 9
- 24
- 
                    1For Webpack 5+, looks like the [CLI syntax for passing env vars](https://webpack.js.org/guides/environment-variables/) has changed to `npx webpack --env goal=local` (without a `.`) – KyleMit Jul 07 '22 at 11:44
