evanw / esbuild

An extremely fast bundler for the web
https://esbuild.github.io/
MIT License
38.18k stars 1.15k forks source link

question: when will esbuild generate __esm for es module #2477

Open hardfist opened 2 years ago

hardfist commented 2 years ago

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.

hyrious commented 2 years ago

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
hardfist commented 2 years ago

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

hyrious commented 2 years ago

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')