Home > Web Front-end > JS Tutorial > body text

How to Pass Environment-Dependent Variables in Webpack?

Linda Hamilton
Release: 2024-11-09 15:08:02
Original
737 people have browsed it

How to Pass Environment-Dependent Variables in Webpack?

Passing Environment-Dependent Variables in Webpack

When migrating an Angular app from Gulp to Webpack, a common task is managing environment-dependent variables. Here are three effective ways to achieve this using Webpack:

1. DefinePlugin

This method directly replaces variables in the HTML page using the DefinePlugin:

new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
})
Copy after login

Note that the string format preserves the variable's environment value.

2. EnvironmentPlugin

EnvironmentPlugin simplifies the DefinePlugin process by mapping environment values to code internally:

new webpack.EnvironmentPlugin(['NODE_ENV'])
Copy after login

3. Alias

For complex configuration needs, you can use an aliased module:

Consumer Side:

var config = require('config');
Copy after login

Configuration Module:

resolve: {
    alias: {
        config: path.join(__dirname, 'config', process.env.NODE_ENV)
    }
}
Copy after login

This allows you to export configuration from a specified module based on the environment variable.

The above is the detailed content of How to Pass Environment-Dependent Variables in Webpack?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template