src/content/guides/environment-variables.mdx
To disambiguate in your webpack.config.js between development and production builds you may use environment variables.
T> webpack's environment variables are different from the environment variables of operating system shells like bash and CMD.exe
The webpack command line environment option --env allows you to pass in as many environment variables as you like. Environment variables will be made accessible in your webpack.config.js. For example, --env production or --env goal=local.
npx webpack --env goal=local --env production --progress
T> Setting up your env variable without assignment, --env production sets env.production to true by default. There are also other syntaxes that you can use. See the webpack CLI documentation for more information.
There is one change that you will have to make to your webpack config. Typically, export default points to the configuration object. To use the env variable, you must make export default a function:
webpack.config.js
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default (env) => {
// Use env.<YOUR VARIABLE> here:
console.log("Goal:", env.goal); // 'local'
console.log("Production:", env.production); // true
return {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
};
};
T> Webpack CLI offers some built-in environment variables which you can access inside a webpack configuration.