Ensuring Core‑JS Tree‑Shaking Works with CommonJS Builds
25K reputation · 02 Oct 2023, 23:52 UTC
Context
For a low‑traffic web app, every kilobyte of JavaScript counts. Core‑JS 3 offers selective imports (e.g., import 'core-js/modules/es.array.flat';) and a runtime detector (import 'core-js/actual';) that can trim polyfills. Babel’s useBuiltIns: "usage" automatically injects only the polyfills that the target browsers actually need. However, Core‑JS ships in both ES‑module and CommonJS bundles, and many build tools default to the CommonJS form. Tree‑shaking only removes unused code when the import graph is statically analyzable, which is true for ES‑module builds but not for CommonJS.
Goal
Identify the precise build‑tool configuration that guarantees Core‑JS ES‑module modules are tree‑shaken, thereby reducing the bundle size for a low‑traffic workload while maintaining full backward‑compatibility for legacy browsers.
Unresolved Decision
It is unclear whether popular bundlers (Webpack, Rollup, Vite) can be instructed to prefer the ES‑module version of Core‑JS automatically, or whether a manual aliasing step is required. Additionally, the interaction between Babel’s useBuiltIns setting and dynamic imports of Core‑JS modules remains ambiguous.
Specific Questions
- Which bundler and aliasing strategy ensure that Core‑JS ES‑module builds are used so that tree‑shaking can remove unused polyfills?
- Does Babel’s
useBuiltIns: "usage"correctly handle dynamic imports of Core‑JS modules when the underlying import is CommonJS? - When using
core-js/actual, can runtime detection safely skip polyfills in modern browsers without causing regressions in older ones?