esbuild 从 0.16到0.17做了哪些破坏性改动
不知道大家有没有遇到过这个问题
Invalid option in build() call: "watch"
/Users/test/node_modules/.pnpm/registry.npmmirror.com+esbuild@0.17.18/node_modules/esbuild/lib/main.js:255:12:
255 │ throw new Error(`Invalid option ${where}: ${quote(key)}`);
出现这个错误的原因是,之前0.16版本时监听文件变化的watch选项是放在options里的
const { build } = require("esbuild");
build({
entryPoints: ['app.js'],
outfile: 'out.js',
bundle: true,
sourcemap: true,
watch:{
onRebuild(){
console.log('rebuild~~~ ');
}
}
})
但是在0.17版本里 options 中的 watch 属性被移除了
不过,别担心,监听文件变更的方法还是有的,watch现在是一个函数,它存在于conetxt这个函数执行后的promise对象中
const { context } = require("esbuild");
context({
entryPoints: ['app.js'],
outfile: 'out.js',
bundle: true,
sourcemap: true,
}).then(ctx=>{
ctx.watch()
})
那么如果我想在文件变更后执行一些操作,或者输出点信息该怎么办呢?以前是通过onRebuild回调来做这些事,但是新版本直接把onRebuild也移除掉了~~~
那现在应该怎么做呢,官方建议通过插件来执行文件变更后的一些操作,以下是正确的例子
const { context } = require("esbuild");
context({
entryPoints: ['app.js'],
outfile: 'out.js',
bundle: true,
sourcemap: true,
plugins: [
{
name: "my-plugin",
setup(build) {
let count = 0;
build.onEnd((result) => {
if (count++ === 0) console.log("first build:", result);
else console.log("subsequent build:", result);
});
},
},
],
}).then(ctx=>{
ctx.watch()
})
😐~查了一下午资料,现在我又可以了,小伙伴们赶紧来点赞吧 ~~~
至于为什么要移除onRebuild,官方的意思是 onRebuild不会在第一次构建时触发(仅在后续构建时触发)这通常是有问题
但是onRebuild的意思不就是重新构建时才触发嘛~~ 这😐