* Applies the plugin by registering its hooks on the compiler. * @param {Compiler} compiler the compiler instance * @returns {void}
(compiler)
| 40 | * @returns {void} |
| 41 | */ |
| 42 | apply(compiler) { |
| 43 | const definePlugin = new DefinePlugin({}); |
| 44 | |
| 45 | compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { |
| 46 | /** @type {Record<string, CodeValue>} */ |
| 47 | const definitions = {}; |
| 48 | for (const key of this.keys) { |
| 49 | const value = |
| 50 | process.env[key] !== undefined |
| 51 | ? process.env[key] |
| 52 | : this.defaultValues[key]; |
| 53 | |
| 54 | if (value === undefined) { |
| 55 | const error = new WebpackError( |
| 56 | `${PLUGIN_NAME} - ${key} environment variable is undefined.\n\n` + |
| 57 | class="st">"You can pass an object with default values to suppress this warning.\n" + |
| 58 | class="st">"See https:class="cm">//webpack.js.org/plugins/environment-plugin for example." |
| 59 | ); |
| 60 | |
| 61 | error.name = class="st">"EnvVariableNotDefinedError"; |
| 62 | compilation.errors.push(error); |
| 63 | } |
| 64 | const defValue = |
| 65 | value === undefined ? class="st">"undefined" : JSON.stringify(value); |
| 66 | definitions[`process.env.${key}`] = defValue; |
| 67 | definitions[`import.meta.env.${key}`] = defValue; |
| 68 | } |
| 69 | definePlugin.definitions = definitions; |
| 70 | }); |
| 71 | definePlugin.apply(compiler); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | module.exports = EnvironmentPlugin; |