We are using WebPack in a single page application. The application is deployed to many environments. We have a requirement where the application needs to call a specific end
I think uglify-loader might do the trick. It provides you more control over the minification result than what you get out of the box.
Webpack externals are a good option to avoid bundle certain dependencies.
However we need to exclude the config.js from minification so that it can be overwritten as part of the deployment process.
Adding a dependency as external not only excludes it from minification but it is not even resolved by webpack.
var webpack = require('webpack');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: './dist',
filename: 'bundle.js'
},
externals: {
'./config': 'config'
}
};
Add as external the path used to require your config.js
. In my simple example the path corresponds to ./config
. Associate it to the global variable that will contain your configuration object. In my case I just used config
as the variable name (see below config.js
).
const config = require('./config');
const endpointUrl = config.env.endpointUrl;
const authUrl = config.env.authUrl;
console.log(endpointUrl);
console.log(authUrl);
As you are preventing webpack to resolve the config.js
module then it has to be available in the environment during runtime. One way could be to expose it as a config
variable in the global context.
window.config = {
env: {
endpointUrl: 'http://1.2.3.4',
authUrl: 'http://5.6.7.8'
}
};
Then you can load a specific config.js
file for any given environment.
<!DOCTYPE html>
<html>
<head>
<title>Webpack</title>
</head>
<body>
<script type="text/javascript" src="config.js"></script>
<script type="text/javascript" src="dist/bundle.js"></script>
</body>
</html>