webpack's core configuration is based on creating and modifying a
potentially unwieldy JavaScript object. While this is OK for configurations
on individual projects, trying to share these objects across projects and
make subsequent modifications gets messy, as you need to have a deep
understanding of the underlying object structure to make those changes.
webpack-chain attempts to improve this process by providing a chainable or
fluent API for creating and modifying webpack configurations. Key portions
of the API can be referenced by user-specified names, which helps to
standardize how to modify a configuration across projects.
This is easier explained through the examples following.
Installation
webpack-chain requires Node.js v6.9 and higher. webpack-chain also
only creates configuration objects designed for use in webpack versions 2, 3,
and 4.
You may install this package using either Yarn or npm (choose one):
Yarn
yarn add --dev webpack-chain
npm
npm install --save-dev webpack-chain
Getting Started
Once you have webpack-chain installed, you can start creating a
webpack configuration. For this guide, our example base configuration will
be webpack.config.js in the root of our project directory.
// Require the webpack-chain module. This module exports a single// constructor function for creating a configuration API.const Config = require('webpack-chain');// Instantiate the configuration with a new APIconst config = new Config();// Make configuration changes using the chain API.// Every API call tracks a change to the stored configuration.config // Interact with entry points .entry('index') .add('src/index.js') .end() // Modify output settings .output .path('dist') .filename('[name].bundle.js');
Having shared configurations is also simple. Just export the configuration
and call .toConfig() prior to passing to webpack.
One of the core API interfaces in webpack-chain is a ChainedMap. A
ChainedMap operates similar to a JavaScript Map, with some conveniences for
chaining and generating configuration. If a property is marked as being a
ChainedMap, it will have an API and methods as described below:
Unless stated otherwise, these methods will return the ChainedMap, allowing
you to chain these methods.
// Remove all entries from a Map.clear()
// Remove a single entry from a Map given its key.// key: *delete(key)
// Fetch the value from a Map located at the corresponding key.// key: *// returns: valueget(key)
// Fetch the value from a Map located at the corresponding key.// If the key is missing, the key is set to the result of function fn.// key: *// fn: Function () -> value// returns: valuegetOrCompute(key, fn)
// Set a value on the Map stored at the `key` location.// key: *// value: *set(key, value)
// Returns `true` or `false` based on whether a Map as has a value set at a// particular key.// key: *// returns: Booleanhas(key)
// Returns an array of all the values stored in the Map.// returns: Arrayvalues()
// Returns an object of all the entries in the backing Map// where the key is the object property, and the value// corresponding to the key. Will return `undefined` if the backing// Map is empty.// This will order properties by their name if the value is// a ChainedMap that used .before() or .after().// returns: Object, undefined if emptyentries()
// Provide an object which maps its properties and values// into the backing Map as keys and values.// You can also provide an array as the second argument// for property names to omit from being merged.// obj: Object// omit: Optional Arraymerge(obj, omit)
// Execute a function against the current configuration context// handler: Function -> ChainedMap // A function which is given a single argument of the ChainedMap instancebatch(handler)
// Conditionally execute a function to continue configuration// condition: Boolean// whenTruthy: Function -> ChainedMap // invoked when condition is truthy, given a single argument of the ChainedMap instance// whenFalsy: Optional Function -> ChainedMap // invoked when condition is falsy, given a single argument of the ChainedMap instancewhen(condition, whenTruthy, whenFalsy)
ChainedSet
Another of the core API interfaces in webpack-chain is a ChainedSet. A
ChainedSet operates similar to a JavaScript Set, with some conveniences for
chaining and generating configuration. If a property is marked as being a
ChainedSet, it will have an API and methods as described below:
Unless stated otherwise, these methods will return the ChainedSet, allowing
you to chain these methods.
// Add/append a value to the end of a Set.// value: *add(value)
// Add a value to the beginning of a Set.// value: *prepend(value)
// Remove all values from a Set.clear()
// Remove a specific value from a Set.// value: *delete(value)
// Returns `true` or `false` based on whether or not the// backing Set contains the specified value.// value: *// returns: Booleanhas(value)
// Returns an array of values contained in the backing Set.// returns: Arrayvalues()
// Concatenates the given array to the end of the backing Set.// arr: Arraymerge(arr)
// Execute a function against the current configuration context// handler: Function -> ChainedSet // A function which is given a single argument of the ChainedSet instancebatch(handler)
// Conditionally execute a function to continue configuration// condition: Boolean// whenTruthy: Function -> ChainedSet // invoked when condition is truthy, given a single argument of the ChainedSet instance// whenFalsy: Optional Function -> ChainedSet // invoked when condition is falsy, given a single argument of the ChainedSet instancewhen(condition, whenTruthy, whenFalsy)
Shorthand methods
A number of shorthand methods exist for setting a value on a ChainedMap
with the same key as the shorthand method name.
For example, devServer.hot is a shorthand method, so it can be used as:
// A shorthand method for setting a value on a ChainedMapdevServer.hot(true);// This would be equivalent to:devServer.set('hot', true);
A shorthand method is chainable, so calling it will return the original
instance, allowing you to continue to chain.
Config
Create a new configuration object.
const Config = require('webpack-chain');const config = new Config();
Moving to deeper points in the API will change the context of what you
are modifying. You can move back to the higher context by either referencing
the top-level config again, or by calling .end() to move up one level.
If you are familiar with jQuery, .end() works similarly. All API calls
will return the API instance at the current context unless otherwise
specified. This is so you may chain API calls continuously if desired.
For details on the specific values that are valid for all shorthand and
low-level methods, please refer to their corresponding name in the
webpack docs hierarchy.
// Backed at config.optimization.minimizersconfig.optimization .minimizer(name) : ChainedMap
Config optimization minimizers: adding
NOTE: Do not use new to create the minimizer plugin, as this will be done for you.
config.optimization .minimizer(name) .use(WebpackPlugin, args)// Examplesconfig.optimization .minimizer('css') .use(OptimizeCSSAssetsPlugin, [{ cssProcessorOptions: { safe: true } }])// Minimizer plugins can also be specified by their path, allowing the expensive require()s to be// skipped in cases where the plugin or webpack configuration won't end up being used.config.optimization .minimizer('css') .use(require.resolve('optimize-css-assets-webpack-plugin'), [{ cssProcessorOptions: { safe: true } }])
config.optimization .minimizer(name) .init((Plugin, args) => new Plugin(...args));
Config optimization minimizers: removing
config.optimization.minimizers.delete(name)
Config plugins
// Backed at config.pluginsconfig.plugin(name) : ChainedMap
Config plugins: adding
NOTE: Do not use new to create the plugin, as this will be done for you.
config .plugin(name) .use(WebpackPlugin, args)// Examplesconfig .plugin('hot') .use(webpack.HotModuleReplacementPlugin);// Plugins can also be specified by their path, allowing the expensive require()s to be// skipped in cases where the plugin or webpack configuration won't end up being used.config .plugin('env') .use(require.resolve('webpack/lib/EnvironmentPlugin'), [{ 'VAR': false }]);
config.resolve .plugin(name) .init((Plugin, args) => new Plugin(...args))
Config resolve plugins: removing
config.resolve.plugins.delete(name)
Config resolve plugins: ordering before
Specify that the current plugin context should operate before another named
plugin. You cannot use both .before() and .after() on the same resolve
plugin.
Specify that the current plugin context should operate after another named
plugin. You cannot use both .before() and .after() on the same resolve
plugin.
webpack-chain supports merging in an object to the configuration instance which
matches a layout similar to how the webpack-chain schema is laid out.
Note: This object does not match the webpack configuration schema exactly
(for example the [name] keys for entry/rules/plugins), so you may need to transform
webpack configuration objects (such as those output by webpack-chain's .toConfig())
to match the layout below prior to passing to .merge().
When working with instances of ChainedMap and ChainedSet, you can perform
conditional configuration using when. You must specify an expression to
when() which will be evaluated for truthiness or falsiness. If the expression
is truthy, the first function argument will be invoked with an instance of the
current chained instance. You can optionally provide a second function to be
invoked when the condition is falsy, which is also given the current chained
instance.
// Example: Only add minify plugin during productionconfig .when(process.env.NODE_ENV === 'production', config => { config .plugin('minify') .use(BabiliWebpackPlugin); });
// Example: Only add minify plugin during production,// otherwise set devtool to source-mapconfig .when(process.env.NODE_ENV === 'production', config => config.plugin('minify').use(BabiliWebpackPlugin), config => config.devtool('source-map') );
Inspecting generated configuration
You can inspect the generated webpack config using config.toString(). This
will generate a stringified version of the config with comment hints for named
rules, uses and plugins:
By default the generated string cannot be used directly as real webpack config
if it contains objects and plugins that need to be required. In order to
generate usable config, you can customize how objects and plugins are
stringified by setting a special __expression property on them: