alphagov / govuk-frontend

GOV.UK Frontend contains the code you need to start building a user interface for government platforms and services.
https://frontend.design-system.service.gov.uk/
MIT License
1.18k stars 325 forks source link

Investigate tree shaking of common js utilities #4964

Closed owenatgov closed 6 months ago

owenatgov commented 6 months ago

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

romaricpascal commented 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

romaricpascal commented 6 months ago

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:

I'll raise a PR that amends our configuration to use the production mode, but not mangle class, function and variable names for testing.