'Webpack conditional build based on configuration values

I'm looking for what ultimately would be a Webpack equivalent to Require.JS's has.js integration.

In Require.JS you can compile different code paths based on a variable in has.js. Is there an equivalent loader/plugin for Webpack to do the same thing?

Example:

config.js

module.exports = {
  option1: 'foo' // other option is 'bar'
}

then in code somewhere have something like the following

code.js

var a;

if (option1 === 'foo') {
  a = require('fooModule');
} else if (option1 === 'bar') {
  a = require('barModule');
}

and have a build only output the code in the condition that evaluates as true?

Alternatively, something like this would work, as well:

import MyLibrary from './modules/' + config.option1 + 'Module.js';

would this stackoverflow answer be the current best practice to achieve what i'm looking for? ultimately, the goal is to have a single set of source that can compile down to specific(ish) targets based on values in a configuration, while not sending non-applicable code down the wire as well in the final build.



Solution 1:[1]

You could use the webpack DefinePlugin to do this. Pete Hunt's Webpack Howto has a good example of implementation.

Solution 2:[2]

It seems the best, most webpack idiomatic way to handle this is through the

Webpack DefinePlugin

Solution 3:[3]

The webpack-hasjs-plugin should do what you want.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JDB
Solution 2 mindpivot
Solution 3 chuckd