准备使用 esbuild 编译园子的 vscode 扩展 ,参考 vscode-postfix-ts/build.mjs 创建了下面的 build.mjs
import esbuild from 'esbuild'
import * as process from 'node:process'
const isProduction = process.argv.includes('--production')
/** @type {esbuild.BuildOptions} */
const options = {
entryPoints: ['./src/extension.ts'],
bundle: true,
outdir: 'out',
external: ['vscode'],
format: 'cjs',
sourcemap: !isProduction,
minify: isProduction,
platform: 'node'
}
await esbuild.build(options)
build 时出现下面的错误
$ node ./build.mjs
X [ERROR] Could not resolve "./presets"
node_modules/@cnblogs/markdown-it-presets/dist/es2015/index.mjs:1:14:
1 │ export * from './presets';
请问如何解决?
找到一个解决方法,可以通过 external
配置参数将上面报错的 npm 包从 esbuild bundle 中排除
external: ['vscode', '@cnblogs/markdown-it-presets']
esbuid 帮助文档中对 external 参数的说明:
You can mark a file or a package as external to exclude it from your build. Instead of being bundled, the import will be preserved and will be evaluated at run time instead.
github 上的相关 issue: Option to treat all node modules as external
还有一个更简单更彻底的解决方法,使用 packages 配置项
packages: 'external'
Use this setting to exclude all of your package's dependencies from the bundle.
与 github 上的 issue import could not resolve 是同一个问题
上面的 external
与 packages
解决方法都需要另外复制 node_modules 中包文件,真正的最佳解决方法是通过 resolveExtensions 配置项添加更多的扩展名,默认支持的扩展名是 ['.ts', '.js']
,这里需要再加上 '.mjs'
resolveExtensions: ['.ts', '.js', '.mjs']