推荐答案
// www.javascriptcn.com code example
import rollup from 'rollup';
async function build() {
// 创建一个 bundle
const bundle = await rollup.rollup({
input: 'src/main.js', // 入口文件
plugins: [
// 在这里添加插件
]
});
// 生成输出文件
await bundle.write({
file: 'dist/bundle.js', // 输出文件路径
format: 'iife', // 输出格式 (iife, cjs, esm, umd, amd)
name: 'MyBundle', // 用于 UMD/IIFE 格式的全局变量名
sourcemap: true // 生成 sourcemap
});
// 关闭 bundle
await bundle.close();
}
build().catch(error => {
console.error(error);
});本题详细解读
1. 引入 Rollup
首先,你需要引入 Rollup 模块。Rollup 提供了一个 rollup 函数,用于创建和配置构建过程。
import rollup from 'rollup';
2. 创建 Bundle
使用 rollup.rollup 函数创建一个 bundle。这个函数接受一个配置对象作为参数,其中 input 是必须的,指定了入口文件。
const bundle = await rollup.rollup({
input: 'src/main.js', // 入口文件
plugins: [
// 在这里添加插件
]
});3. 生成输出文件
创建 bundle 后,你可以使用 bundle.write 方法将 bundle 写入到文件中。write 方法接受一个配置对象,指定输出文件的路径、格式、全局变量名等。
await bundle.write({
file: 'dist/bundle.js', // 输出文件路径
format: 'iife', // 输出格式 (iife, cjs, esm, umd, amd)
name: 'MyBundle', // 用于 UMD/IIFE 格式的全局变量名
sourcemap: true // 生成 sourcemap
});4. 关闭 Bundle
最后,使用 bundle.close 方法关闭 bundle,释放资源。
await bundle.close();
5. 错误处理
在构建过程中,可能会遇到错误。为了确保错误能够被捕获和处理,建议将整个构建过程放在 try-catch 块中,或者使用 .catch 方法来捕获错误。
build().catch(error => {
console.error(error);
});通过以上步骤,你可以使用 Rollup 的 API 进行构建,并生成所需的输出文件。