karmasagent karmasagent - 4 months ago 38
React JSX Question

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?



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

then in code somewhere have something like the following


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.

Ian Ian

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