CodeCoupler Webpack Optimize Bundle Size
To use external libraries, install them with npm install PACKAGENAME, then use them with
import or require in your code. This will include the libraries in your bundle. For
web applications, this may be a negligible inconvenience, but for libraries, it could be fatal.
Always analyze your bundle and check if any dependencies have been included. You should always consider excluding them from your bundle. To analyze your bundle run:
Externalize with Simple Configuration
CodeCoupler Webpack uses the Plugin CodeCoupler Webpack Externals Plugin for this, which makes
the entire configuration process extremely easy. Simply add the necessary entries to the externals
configuration option for each imported package to exclude them from your bundle 1.
This configuration option is an array of objects for each package you want to externalize. Each object needs the following properties:
- module: The name of the package (corresponds to the package name).
- global: Optional. The name of theglobal variable to access the library provided by the package.
- entries: Optional. String or an array of strings. Names of
jsorcssfiles to copy from the modules folder to thedistfolder and inject links to them into your HTML files. - copy: Optional. String or array of strings. Globs to copy from the modules folder to the
distfolder. This can be used to copy assets like fonts.
Example
Here is an example that you can use after installing the packages jquery, bootstrap and
@fortawesome/fontawsome-free to copy and inject into all libraries, stylesheets and other assets.
First install the packages:
Then extend the CodeCoupler Webpack configuration in your webpack.config.js with the property
externals:
With this configuration the packages will not be included in your bundle. The assets defined in
entries and copy will be copied into your dist/vendor folder, and links to these assets will
be injected into your HTML files.
Try this out by running the following command and inspecting the results in the dist directory:
You can also build a version where the modules are not copied and the links are injected to point to a CDN. Try this:
Read more details here: The configuration reference
-
Until version 3, the configuration must be placed in a file called
webpack.externals.configin the project's root directory. In this file the array must be exported withmodule.exports = []. ↩