I need to use a library in the webpack config to get the username of the individual doing the build. I am using the npm 'username' package which is asynchronous and returns a promise when the username is obtained.
const username = require('username');
username().then(username => { });
The webpack documentation describes one type of configuration to return a promise
module.exports = () => { return new Promise((resolve, reject) => {})}
and another type of configuration to use environment variables from the CLI command line
module.exports = function(env) {}
, but not how to use the two together.
I need to be able to read-in from the command line the environment variables --env=prod
set from the CLI as follows in the package.json
"scripts": {
"start": "webpack-dev-server --env=local --port=4200 --history-api-fallback",
"build": "webpack",
"build-dev": "rimraf dist && webpack --env=dev --colors --bail",
"build-prod": "rimraf dist && webpack -p --env=prod --colors --bail",
"test": "karma start ./karma.conf.js"
},
After some trial and error, I found it is possible to combine the two config file techniques, you can have the exports set to the function which will give you the environment variables, and then this function can return a promise itself, and the promise can return the config.
In this way you can have the result of the promise and the environment variables both available in the configuration for webpack.
module.exports = function(env) {
console.log(`Building target environment: ${env}`);
return username().then(username => {
return {
"devtool": "source-map",
// ... original config here
};
});
};