Exclude module from webpack minification

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.

webpack.config.js

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).

index.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.

config.js

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.

index.html

<!DOCTYPE html>
<html>
<head>
  <title>Webpack</title>
</head>
<body>
  <script type="text/javascript" src="https://stackoverflow.com/questions/33915826/config.js"></script>
  <script type="text/javascript" src="dist/bundle.js"></script>
</body>
</html>

Leave a Comment