question: when will esbuild generate __esm for es module
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

-
generated code

Searching "WrapESM" in the source:
https://github.com/evanw/esbuild/blob/6d4f9028083b8f9bf77be9492d713d6c2294959e/internal/bundler/linker.go#L1293-L1313
Basically two circumstances:
- You are using
require()to import an ESM module. - You does not enable
splitting, then any dynamic import will result in the dependency be wrapped in__esm. See it in REPL
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
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')