使用 rollup.watch

起步

新建文件 rollup.watch.js (文件名任意)

内部代码格式如下:

const rollup = require('rollup');

const watchOptions = {...};
const watcher = rollup.watch(watchOptions);

watcher.on('event', event => {
  // event.code 会是下面其中一个:
  //   START        — 监听器正在启动(重启)
  //   BUNDLE_START — 构建单个文件束
  //   BUNDLE_END   — 完成文件束构建
  //   END          — 完成所有文件束构建
  //   ERROR        — 构建时遇到错误
  //   FATAL        — 遇到无可修复的错误
});

// 停止监听
watcher.close();

其中,watchOptions 为与 rollup.config.js 内相似内容:

// rollup.config.js
export default {
	input: 'src/main.js',
	output: {
		file: 'bundle.js',
		format: 'cjs'
	}
}

rollup.watch.js 中的内容如下:

// 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 时生效。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值