Home  >  Article  >  Web Front-end  >  How to Pass Environment-Dependent Variables in Your Angular Application Using Webpack?

How to Pass Environment-Dependent Variables in Your Angular Application Using Webpack?

DDD
DDDOriginal
2024-11-10 21:04:02644browse

How to Pass Environment-Dependent Variables in Your Angular Application Using Webpack?

Passing Environment-Dependent Variables in webpack

Problem:

Converting an Angular application from gulp to webpack, you need to find a way to replace environment-dependent variables (such as the database name) in the HTML page.

Solution:

There are several methods to accomplish this using webpack:

DefinePlugin

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

DefinePlugin replaces exact matches "as is," hence the JSON-formatted string.

EnvironmentPlugin

new webpack.EnvironmentPlugin(['NODE_ENV'])

EnvironmentPlugin uses DefinePlugin internally to map environment values through Terser syntax.

Alias

Create an aliased module to consume configuration:

// Consumer module
var config = require('config');
// Configuration module
resolve: {
    alias: {
        config: path.join(__dirname, 'config', process.env.NODE_ENV)
    }
}

For example, if process.env.NODE_ENV is 'development,' the aliased module would be located at ./config/development.js:

// Configuration module for 'development' environment
module.exports = {
    testing: 'something',
    ...
};

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

Statement:
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