Similar to webpack.EnvironmentPlugin, but for the import.meta.env object.
npm install --save-dev import-meta-env-webpack-pluginThe ImportMetaEnvWebpackPlugin accepts either an array of keys or an object mapping its keys to their default values.
const {
ImportMetaEnvWebpackPlugin,
} = require("import-meta-env-webpack-plugin");
new ImportMetaEnvWebpackPlugin(["NAME", "DEBUG"]);This is equivalent to the following DefinePlugin application:
new webpack.DefinePlugin({
"import.meta.env.NAME": JSON.stringify(process.env.NAME),
"import.meta.env.DEBUG": JSON.stringify(process.env.DEBUG),
});Not specifying the environment variable raises an "
EnvironmentPlugin-${key}environment variable is undefined" error.
Alternatively, the ImportMetaEnvWebpackPlugin supports an object, which maps keys to their default values. The default value for a key is taken if the key is undefined in process.env.
new ImportMetaEnvWebpackPlugin({
NAME: "world", // use 'world' unless process.env.NAME is defined
DEBUG: false,
});Variables coming from
process.envare always strings.
Default values of
nullandundefinedbehave differently. Useundefinedfor variables that must be provided during bundling, ornullif they are optional.
Let's investigate the result when running the previous ImportMetaEnvWebpackPlugin configuration on a test file entry.js:
if (import.meta.env.NAME === "webpack") {
console.log("Welcome to webpack");
}
if (import.meta.env.DEBUG) {
console.log("Debugging output");
}When executing NAME=webpack webpack in the terminal to build, entry.js becomes this:
if ("webpack" === "webpack") {
// <-- 'webpack' from NAME is taken
console.log("Welcome to webpack");
}
if (false) {
// <-- default value is taken
console.log("Debugging output");
}Running DEBUG=false webpack yields:
if ("world" === "webpack") {
// <-- default value is taken
console.log("Welcome to webpack");
}
if ("false") {
// <-- 'false' from DEBUG is taken
console.log("Debugging output");
}See webpack.EnvironmentPlugin for more details.