跳到主要内容

rollup.watch

2023年03月05日
柏拉文
越努力,越幸运

一、认识


二、语法


三、用法


可以通过 rollup.watch 来完成 watch 模式下的打包,即每次源文件变动后自动进行重新打包。你可以新建watch.js文件,内容入下:

// watch.js
const rollup = require("rollup");

const watcher = rollup.watch({
// 和 rollup 配置文件中的属性基本一致,只不过多了`watch`配置
input: "./src/index.js",
output: [
{
dir: "dist/es",
format: "esm",
},
{
dir: "dist/cjs",
format: "cjs",
},
],
watch: {
exclude: ["node_modules/**"],
include: ["src/**"],
},
});

// 监听 watch 各种事件
watcher.on("restart", () => {
console.log("重新构建...");
});

watcher.on("change", (id) => {
console.log("发生变动的模块id: ", id);
});

watcher.on("event", (e) => {
if (e.code === "BUNDLE_END") {
console.log("打包信息:", e);
}
});

现在你可以通过执行 node watch.js 开启 Rollupwatch 打包模式,当你改动一个文件后可以看到如下的日志,说明 Rollup 自动进行了重新打包,并触发相应的事件回调函数:


发生生变动的模块id: /xxx/src/index.js
重新构建...
打包信息: {
code: 'BUNDLE_END',
duration: 10,
input: './src/index.js',
output: [
// 输出产物路径
],
result: {
cache: { /* 产物具体信息 */ },
close: [AsyncFunction: close],
closed: false,
generate: [AsyncFunction: generate],
watchFiles: [
// 监听文件列表
],
write: [AsyncFunction: write]
}
}