I want to pass custom parameters from command line. Something like this:
webpack-dev-server --inline --hot --customparam1=value
Exactly what I am trying to achieve is that I am working on a vue-loader application. The application has certain services that fetch data.
I have another application that acts as the api server. We need the application to run in 2 ways (because all members of our team don't have access to the api server)
So that service has 2 ways to get data:
1) If api server is running(for dev team), use http calls to get the data from localhost
2) If api server is not running(for design team), simply use static data already there in services:
var someData;
if (customparam1 === "withApi"){
someData=getData("http://localhost:8081/apiendpoint");
} else {
someData=[
{a:b},
{c:d},
// more custom array of static data
.....
]
}
So this customparam1 is supposed to be passed from webpack-dev-server command line and as per this documentation, no such way exists that I could find(did I miss something?)
How do I do it?
PS: I am on webpack 1.12.1
Update: 2020 / 2 / 16
If you are using webpack4 or the latest one, using the environment variables is very handy!
The webpack command line environment option --env allows you to pass in as many environment variables as you like. Environment variables will be made accessible in your webpack.config.js. For example, --env.production or --env.NODE_ENV=local (NODE_ENV is conventionally used to define the environment type, see here.)
For example, the command is like:
env.NODE_ENV=development webpack-dev-server
Inside the webpack.config.js, we can define the env variable inside new webpack.DefinePlugin()
to make it available in the app.
webpack.config.js:(plugin)
// pass the env and return the webpack setting
module.exports = env => {
console.log(env);
return {
....
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.pug",
inject: false
}),
new webpack.DefinePlugin({ customparam1: JSON.stringify(env.customparam1) })
],
}
]
....
}
};
};
Check react-create-app doc, the variable will start with REACT_APP_
command:
REACT_APP_CUSTOM_VARIABLE=234 npm run dev
app:
console.log(process.env.REACT_APP_CUSTOM_VARIABLE) // 234
command:
webpack-dev-server --customparam1=value
webpack.config.js:
var path = require("path");
var webpack = require("webpack");
function findPara(param){
let result = '';
process.argv.forEach((argv)=>{
if(argv.indexOf('--' + param) === -1) return;
result = argv.split('=')[1];
});
return result;
}
const customparam1 = findPara('customparam1');
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
customparam1:JSON.stringify(customparam1)
})
]
};
main js file:
if(customparam1 === xxx){ ... }