Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing environment-dependent variables in webpack

I'm trying to convert an angular app from gulp to webpack. in gulp I use gulp-preprocess to replace some variables in the html page (e.g. database name) depending on the NODE_ENV. What is the best way of achieving a similar result with webpack?

like image 383
kpg Avatar asked May 04 '15 12:05

kpg


People also ask

Does webpack set Node_env?

env. NODE_ENV is not set to 'production' within the build script webpack. config.

Can I have multiple .env files?

One solution is to have multiple . env files which each represent different environments. In practice this means you create a file for each of your environments: .


1 Answers

There are two basic ways to achieve this.

DefinePlugin

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

Note that this will just replace the matches "as is". That's why the string is in the format it is. You could have a more complex structure, such as an object there but you get the idea.

EnvironmentPlugin

new webpack.EnvironmentPlugin(['NODE_ENV']) 

EnvironmentPlugin uses DefinePlugin internally and maps the environment values to code through it. Terser syntax.

Alias

Alternatively you could consume configuration through an aliased module. From consumer side it would look like this:

var config = require('config'); 

Configuration itself could look like this:

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

Let's say process.env.NODE_ENV is development. It would map into ./config/development.js then. The module it maps to can export configuration like this:

module.exports = {     testing: 'something',     ... }; 
like image 141
Juho Vepsäläinen Avatar answered Sep 30 '22 18:09

Juho Vepsäläinen