CodeCoupler Webpack Optimize Bundle Size
To use external libraries you have to install them with npm install PACKAGENAME
and use them with
import
or require
in your code. Doing this the libraries will be included in your bundle. For
web applications, this may be a negligible inconvenience, but for libraries, could it be fatal.
Always analyse your bundle and check if any dependency have been included. You should always consider to exclude them from your bundle. To analyze your bundle run:
Externalize with Simple Configuration
CodeCoupler Webpack
use for this the Plugin CodeCoupler Webpack Externals Plugin
, which makes
the whole configuration extremely easy. Just add the necessary entries to the externals
configuration option for every imported package, to exclude them from your bundle 1.
The configuration option is an array of objects for each package you want to externalize. Each object need the following properties:
- module: The name of the package (corresponds to the package name).
- global: Optional. The global variable name to access the library provided by the package.
- entries: Optional. String or array of strings. Name of
js
orcss
files to copy from the modules folder to thedist
folder 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
dist
folder. This can be used to copy assets like fonts.
Example
Here an example that you can use after installing the packages jquery
, bootstrap
and
@fortawesome/fontawsome-free
to copy and inject 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 into your bundle. The assets defined in
entries
and copy
will be copied into your dist/vendor
folder and your HTML files will be
injected with links to these assets.
Try this out by running the following command and inspecting the results in the dist
directory:
Furthermore you can build a version where the modules will not copied and the injected links will point to a CDN. Try this:
Important Note: Using Vue
Pay particular attention to whether you are importing parts of the Vue library. The library is
pre-installed with CodeCoupler Webpack
and this is easily overlooked (because you do not need to
install the package). A statement such as import { toRaw } from "vue"
or just using .vue
files
can result in the Vue library being included in the bundle. This leads to complications if the
target project use its own version of Vue.
To exclude the Vue library from the build result. Add the following to the externals
array:
Read more details here: The configuration reference
-
Till version 3 the configuration must be placed in a file
webpack.externals.config
in the project root directory. The array must be exported in this file withmodule.exports = []
. ↩