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 NO
To add to the bunch of answers personally I prefer the following:
const webpack = require('webpack');
const prod = process.argv.indexOf('-p') !== -1;
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
process: {
env: {
NODE_ENV: prod? `"production"`: '"development"'
}
}
}),
...
]
};
Using this there is no funky env variable or cross-platform problems (with env vars). All you do is run the normal webpack
or webpack -p
for dev or production respectively.
Reference: Github issue
I prefer using .env file for different environment.
env.dev
to .env into root folder env.prod
to .envand in code
use
require('dotenv').config();
const API = process.env.API ## which will store the value from .env file
now 2020, i am face to same question, but for this old question, there are so many new answer, just list some of it:
plugins: [
new HtmlWebpackPlugin({
// 1. title is the parameter, you can use in ejs template
templateParameters:{
title: JSON.stringify(someting: 'something'),
},
}),
//2. BUILT_AT is a parameter too. can use it.
new webpack.DefinePlugin({
BUILT_AT: webpack.DefinePlugin.runtimeValue(Date.now,"some"),
}),
//3. for webpack5, you can use global variable: __webpack_hash__
//new webpack.ExtendedAPIPlugin()
],
//4. this is not variable, this is module, so use 'import tt' to use it.
externals: {
'ex_title': JSON.stringify({
tt: 'eitentitle',
})
},
the 4 ways only basic, there are even more ways that i believe. but i think maybe this 4ways is the most simple.
You can directly use the EnvironmentPlugin available in webpack
to have access to any environment variable during the transpilation.
You just have to declare the plugin in your webpack.config.js
file:
var webpack = require('webpack');
module.exports = {
/* ... */
plugins = [
new webpack.EnvironmentPlugin(['NODE_ENV'])
]
};
Note that you must declare explicitly the name of the environment variables you want to use.
Since Webpack v4, simply setting mode
in your Webpack config will set the NODE_ENV
for you (via DefinePlugin
). Docs here.
To add to the bunch of answers:
Use ExtendedDefinePlugin instead of DefinePlugin
npm install extended-define-webpack-plugin --save-dev.
ExtendedDefinePlugin is much simpler to use and is documented :-) link
Because DefinePlugin lacks good documentation, I want to help out, by saying that it actually works like #DEFINE in c#.
#if (DEBUG)
Console.WriteLine("Debugging is enabled.");
#endif
Thus, if you want to understand how DefinePlugin works, read the c# #define doucmentation. link