Closed owenatgov closed 6 months ago
The issue appears to be Webpack specific. For Rollup and Vite[^1], functions fromcommon/index.mjs
that are not used by the Button component, like getFragmentFromURL
, are properly absent from the built single-component.js
.
[^1]: Vite was tested by building a single entry point to avoid the issue listed in https://github.com/alphagov/govuk-frontend/issues/4978 regarding how code is split by Vite automatically
Looks like the reason is that our Webpack configuration does not include the Terser plugin, used for removing dead code. Looking at Webpack's documentation about tree-shaking, it seems that tree-shaking is a two step thing for Webpack:
usedExports
will make Webpack include a whole module, but not export whichever of its exports are not used by other modules, effectively making it dead code in the file. This step is explained at the end of the 'Add a Utility' sectionmode: production
is set. That part is explained in the 'Minify the Output' section.I'll raise a PR that amends our configuration to use the production mode, but not mangle class, function and variable names for testing.
What
Investigate ways to ensure that our common js utilities, primarily the multiple modules in common/index/mjs, are correctly tree-shaken when bundled. This includes but is not limited to splitting the modules in index.mjs into their own files.
Why
We found during https://github.com/alphagov/govuk-frontend/issues/4957 that whilst we were able to effectively get tree shaking to work as expected for components, bundlers were importing all of common/index.mjs when not all of common was being used. It would be good to further optimise our js and understand why our
"sideEffects": true
solution in https://github.com/alphagov/govuk-frontend/pull/4961 didn't work for common.Who needs to work on this
Developers
Who needs to review this
Developers
Done when