起步
新建文件 rollup.watch.js (文件名任意)
内部代码格式如下:
const rollup = require('rollup');
const watchOptions = {...};
const watcher = rollup.watch(watchOptions);
watcher.on('event', event => {
});
watcher.close();
其中,watchOptions 为与 rollup.config.js 内相似内容:
export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
}
}
rollup.watch.js 中的内容如下:
const rollup = require('rollup');
const watchOptions = {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
}
}
const watcher = rollup.watch(watchOptions);
console.log('Rollup is watching for changes...');
watcher.on('event', event => {
switch (event.code) {
case 'START':
console.info('Rebuilding...');
break;
case 'BUNDLE_START':
console.info('Bundling...');
break;
case 'BUNDLE_END':
console.info('Bundled!');
break;
case 'END':
console.info('Done!');
break;
case 'ERROR':
case 'FATAL':
console.error("Rollup error: ", event);
}
});
process.on('exit', () => {
watcher.close();
});
使用插件:
const { nodeResolve } = require("@rollup/plugin-node-resolve");
const commonjs = require("@rollup/plugin-commonjs");
const watchOptions = {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
},
plugins: [
nodeResolve(),
commonjs()
]
}
使用 Nodejs 运行代码:
node rollup.watch.js
此时,控制台输出内容:
Rollup is watching for changes...
Rebuilding...
Bundling...
Bundled!
Done!
此时,修改任意文件,项目会被实时打包。
Watch 选项
Watch options
const watchOptions = {
watch: {
chokidar,
include,
exclude
}
};
这些选项仅在运行 Rollup 时使用 --watch 标志或使用 rollup.watch 时生效。
|