esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

question: when will esbuild generate __esm for es module

Open hardfist opened this issue 3 years ago • 3 comments

I met an case which esm treeshaking not working, but it's hard to make a minimal reproducible demo. It's odd that the esm module generates an __esm wrapper for esm exports, which I think maybe related to the problem.

  • components/index.js image

  • generated code image

hardfist avatar Aug 17 '22 07:08 hardfist

Searching "WrapESM" in the source:

https://github.com/evanw/esbuild/blob/6d4f9028083b8f9bf77be9492d713d6c2294959e/internal/bundler/linker.go#L1293-L1313

Basically two circumstances:

  1. You are using require() to import an ESM module.
  2. You does not enable splitting, then any dynamic import will result in the dependency be wrapped in __esm. See it in REPL

hyrious avatar Aug 17 '22 09:08 hyrious

I finally find the reason why tree shaking fails, because some one use dynamic import, which will make tree shaking fail, It seems fail both in rollup and webpack. you can see it in repl

hardfist avatar Aug 17 '22 10:08 hardfist

There's a workaround to still apply tree-shaking to lazy modules -- add a wrapper to re-export names you need:

// components.js
export let a = 1
export let b = 2

// wrapper.js, manually export used names
export { a } from './components'

// main.js
const { a } = await import('./wrapper')

hyrious avatar Aug 17 '22 23:08 hyrious