The externals
configuration option provides a way of excluding dependencies from the output bundles. Instead, the created bundle relies on that dependency to be present in the consumer's environment. This feature is typically most useful to library developers, however there are a variety of applications for it.
consumer here is any end user application that includes the library that you have bundled using webpack.
externals
string
array
object
function
regex
Prevent bundling of certain import
ed packages and instead retrieve these external dependencies at runtime.
For example, to include jQuery from a CDN instead of bundling it:
index.html
... <script src="https://code.jquery.com/jquery-3.1.0.js" integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk=" crossorigin="anonymous"></script> ...
webpack.config.js
externals: { jquery: 'jQuery' }
This leaves any dependant modules unchanged, i.e. the code shown below will still work:
import $ from 'jquery'; $('.my-element').animate(...);
The bundle with external dependencies can be used in various module contexts, such as CommonJS, AMD, global and ES2015 modules. The external library may be available in any of these forms:
module.exports.default
.externals
accepts various syntax and interprets them in different manners.
jQuery
in the externals indicates that your bundle will need jQuery
variable in the global form.
externals: { subtract: ['./math', 'subtract'] }
subtract: ['./math', 'subtract']
converts to a parent child construct, where ./math
is the parent module and your bundle only requires the subset under subtract
variable.
externals : { react: 'react' } // or externals : { lodash : { commonjs: "lodash", amd: "lodash", root: "_" // indicates global variable } }
This syntax is used to describe all the possible ways that an external library can be available. lodash
here is available as lodash
under AMD and CommonJS module systems but available as _
in a global variable form.
It might be useful to define your own function to control the behavior of what you want to externalize from webpack. webpack-node-externals, for example, excludes all modules from the node_modules and provides some options to, for example, whitelist packages.
It basically comes down to this:
externals: [ function(context, request, callback) { if (/^yourregex$/.test(request)){ return callback(null, 'commonjs ' + request); } callback(); } ],
The 'commonjs ' + request
defines the type of module that needs to be externalized.
Every dependency that matches the given regular expression will be excluded from the output bundles.
externals: /^(jquery|\$)$/i
In this case any dependency named jQuery
, capitalized or not, or $
would be externalized.
For more information on how to use this configuration, please refer to the article on how to author a library.
© 2012–2016 Tobias Koppers
Licensed under the Creative Commons Attribution License 4.0.
https://webpack.js.org/configuration/externals/