Search code examples
javascriptperformancerollupjs

How to determine why something is imported in a Rollup chunk?


The content of the question is that I am analyzing why does my bundle include a lot of unused code.

enter image description here

In the screenshot, I see that there is a chunk being loaded called chunk-index.es.fbfa066e.js. 76% of that code is unused after loading the app.

If I look at the contents of this module, it basically bundles 3 other packages.

// @preserve module @/node_modules/.pnpm/[email protected]/node_modules/is-plain-object/dist/is-plain-object.mjs
// @preserve module @/node_modules/.pnpm/[email protected]/node_modules/immer/dist/immer.esm.mjs
// @preserve module @/node_modules/.pnpm/[email protected]/node_modules/slate/dist/index.es.js

ane exports them as

export {
  Element as E,
  Node as N,
  Operation as O,
  Path as P,
  Range as R,
  Scrubber as S,
  Transforms as T,
  Editor as a,
  Text as b,
  Point as c,
  createEditor as d,
  isPlainObject as i
};

Now if I look at the initiated projects.page.client.f6019eee.js

enter image description here However, the only reference to this module inside of projects.page.client is this import:

import "../../../chunk-Table.31bce020.js";
import "../../../chunk-index.es.fbfa066e.js";
import "../../../chunk-Tabs.0cbe576c.js";

i.e. It does not even import any of the named exports.

  • Why is chunk-index.es.fbfa066e.js import included in projects.page.client.f6019eee.js? (and how to debug this?)
  • How does projects.page.client.f6019eee.js use it given that it does not import its exports?
  • How do I tell to not import this chunk?

Solution

  • There are several things at play here:

    • imports magically appearing in your entry points is usually a—harmless—load performance optimization by Rollup. This will not increase the amount of dead code but "hoists" imports that are otherwise imported by some dependency of that chunk to be loaded earlier, see https://rollupjs.org/faqs/#why-do-additional-imports-turn-up-in-my-entry-chunks-when-code-splitting
    • If in the original sources, you are using a lot of reexport why what people call "barrel files", you may want to look into setting treeshake.moduleSideEffects to false, at least for the barrel file. Otherwise, all imports that Rollup "thinks" have side effect of the barrel file will end up as dependencies for all chunks that import that file. Alternatively, do not use such files but directly import from the file that declares the variable. But sometimes that is not possible e.g. for typing reasons.