Skip to content

library and externals

btoo edited this page Jan 4, 2017 · 17 revisions

You developed a library and want to distribute it in compiled/bundled versions (in addition to the modularized version). You want to allow the user to use it in a <script>-tag or with an amd loader (i. e. require.js). Or you depend on various precompilations and want to remove the pain for the user and distribute it as simple compiled commonjs module.

configuration options

Webpack has three configuration options that are relevant for these use cases: output.library, output.libraryTarget and externals.

output.library allows you to optionally specify the name of your library.

output.libraryTarget allows you to specify the type of output. I.e. CommonJs, AMD, for usage in a script tag or as UMD module.

externals allows you to specify dependencies for your library that are not resolved by webpack, but become dependencies of the output. This means they are imported from the environment during runtime.

Examples

Compile library for usage in a <script>-tag

  • depends on "jquery", but jquery should not be included in the bundle.
  • library should be available at Foo in the global context.
var jQuery = require("jquery");
var math = require("math-library");

function Foo() {}

// ...

module.exports = Foo;

Recommended configuration (only relevant stuff):

{
	output: {
		// export itself to a global var
		libraryTarget: "var",
		// name of the global var: "Foo"
		library: "Foo"
	},
	externals: {
		// require("jquery") is external and available
		//  on the global var jQuery
		"jquery": "jQuery"
	}
}

Resulting bundle:

var Foo = (/* ... webpack bootstrap ... */
{
	0: function(...) {
		var jQuery = require(1);
		/* ... */
	},
	1: function(...) {
		module.exports = jQuery;
	},
	/* ... */
});

Applications and externals

You can also use the externals option to import an existing API into applications. For example, if you want to use jQuery from a CDN via a separate <script> tag while still explicitly declaring it as a dependency via require("jquery"), you would specify it as external like so: { externals: { jquery: "jQuery" } }.

Resolving and externals

Externals processing happens before resolving the request, which means you need to specify the unresolved request. Loaders are not applied to externals, so you need to "externalize" a request with a loader: require("bundle!jquery") { externals: { "bundle!jquery": "bundledJQuery" } }