- Notifications
You must be signed in to change notification settings - Fork128
library and externals
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 anamd 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 compiledcommonjs module.
Webpack has threeconfiguration options that are relevant for these use cases:output.library
,output.libraryTarget
andexternals
.
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.
- depends on
"jquery"
, but jquery should not be included in the bundle. - library should be available at
Foo
in the global context.
varjQuery=require("jquery");varmath=require("math-library");functionFoo(){}// ...module.exports=Foo;
Recommended configuration (only relevant stuff):
{output:{// export itself to a global varlibraryTarget:"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:
varFoo=(/* ... webpack bootstrap ... */{0:function(...){varjQuery=require(1);/* ... */},1:function(...){module.exports=jQuery;},/* ... */});
You can also use theexternals
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 viarequire("jquery")
, you would specify it as external like so:{ externals: { jquery: "jQuery" } }
.
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" } }
webpack 👍