Home > Web Front-end > JS Tutorial > 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
Release: 2024-11-10 21:04:02
Original
687 people have browsed it

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')
})
Copy after login

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

EnvironmentPlugin

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

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');
Copy after login
// Configuration module
resolve: {
    alias: {
        config: path.join(__dirname, 'config', process.env.NODE_ENV)
    }
}
Copy after login

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',
    ...
};
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template