跳到主要内容

代码分隔

runEsbuild方法中,针对 ESM 的模块,默认设置splittingtrue

否则,根据 CLI 指令传给esbuildsplitting属性。

const splitting =
format === 'iife'
? false
: typeof options.splitting === 'boolean'
? options.splitting
: format === 'esm'

esbuild({
splitting,
})

针对CJS,使用自定义插件,基于sucrase进行构建。

export const cjsSplitting = (): Plugin => {
return {
name: 'cjs-splitting',

async renderChunk(code, info) {
if (
!this.splitting ||
this.options.treeshake || // <-- handled by rollup
this.format !== 'cjs' ||
info.type !== 'chunk' ||
!/\.(js|cjs)$/.test(info.path)
) {
return
}

const { transform } = await import('sucrase')

const result = transform(code, {
filePath: info.path,
transforms: ['imports'],
sourceMapOptions: this.options.sourcemap
? {
compiledFilename: info.path,
}
: undefined,
})

return {
code: result.code,
map: result.sourceMap,
}
},
}
}