Install dotenv-webpack:
npm install dotenv-webpack --save-dev
Create separate .env files for each environment you want to configure. For example, you might have .env.development for development environment and .env.production for production environment.
Create a .env file containing the common environment variables shared across all environments.
Create a webpack.config.js file that uses dotenv-webpack to load the appropriate environment-specific .env file based on the NODE_ENV environment variable. Here's an example:
const path = require('path');
const webpack = require('webpack');
const Dotenv = require('dotenv-webpack');
module.exports = (env) => {
const isProduction = env.NODE_ENV === 'production';
const dotenvFilename = isProduction ? '.env.production' : '.env.development';
return {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.bundle.js',
},
plugins: [
new Dotenv({
path: dotenvFilename,
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV),
}),
],
};
};
In this example, we're using Dotenv to load the environment variables from the appropriate .env file, based on the NODE_ENV environment variable. We're also using DefinePlugin to define a process.env.NODE_ENV variable that can be used in our code.
- Update your package.json scripts to pass the NODE_ENV environment variable to the webpack command. For example:
{
"scripts": {
"start": "NODE_ENV=development webpack serve --mode development --open",
"build": "NODE_ENV=production webpack --mode production"
}
}
In this example, we're setting the NODE_ENV environment variable to development for the start script, and to production for the build script. Webpack will then use the appropriate .env file based on this environment variable.
And that's it! Now you can use environment-specific .env files with Webpack.
Bonus:
If you don't want to use dotenv-webpack plugins, you can update your webpack config code with
const path = require('path');
const webpack = require('webpack');
module.exports = (env) => {
const isProduction = env.NODE_ENV === 'production';
const envFile = isProduction ? '.env.production' : '.env.development';
const envPath = path.resolve(__dirname, envFile);
const envVars = require('dotenv').config({ path: envPath }).parsed || {};
return {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
plugins: [
new webpack.DefinePlugin({
'process.env': JSON.stringify(envVars),
}),
]
}
};
If NODE_ENV=development
is not working in latest Webpack, use below command
"start": "webpack serve --mode development --env NODE_ENV=development
and now you can access it using env.NODE_ENV
Top comments (0)