Rollup命令行接口完全指南:从配置到高级用法
什么是Rollup命令行接口
Rollup是一个现代化的JavaScript模块打包工具,其命令行接口(CLI)是开发者最常用的交互方式。通过命令行,开发者可以快速启动打包过程、配置构建选项以及集成到自动化流程中。
配置文件基础
虽然Rollup可以直接通过命令行参数使用,但配置文件提供了更强大和便捷的配置方式。配置文件通常命名为rollup.config.js
或rollup.config.mjs
,放置在项目根目录下。
基本配置示例
export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
}
};
配置文件类型支持
Rollup支持多种配置文件格式:
- ES模块(.js或.mjs):使用
export default
导出配置 - CommonJS(.cjs):使用
module.exports
导出配置 - TypeScript(.ts):需要配合
@rollup/plugin-typescript
插件使用
高级配置技巧
多输入多输出配置
Rollup支持通过数组配置实现多输入多输出:
export default [
{
input: 'main-a.js',
output: {
file: 'dist/bundle-a.js',
format: 'cjs'
}
},
{
input: 'main-b.js',
output: [
{
file: 'dist/bundle-b1.js',
format: 'cjs'
},
{
file: 'dist/bundle-b2.js',
format: 'es'
}
]
}
];
异步配置
配置文件可以返回Promise,适合需要动态获取配置的场景:
import fetch from 'node-fetch';
export default fetch('/remote-config-service');
函数式配置
配置文件可以导出函数,接收命令行参数实现动态配置:
export default (commandLineArgs) => {
return {
input: commandLineArgs.input || 'main.js',
output: {
file: 'bundle.js',
format: 'cjs'
}
};
};
配置智能提示
TypeScript类型支持
Rollup提供了完善的TypeScript类型定义,可以通过以下方式获得IDE智能提示:
/**
* @type {import('rollup').RollupOptions}
*/
const config = {
// 你的配置
};
export default config;
或者使用defineConfig
辅助函数:
import { defineConfig } from 'rollup';
export default defineConfig({
// 你的配置
});
命令行参数详解
Rollup提供了丰富的命令行参数,以下是一些常用参数分类说明:
基础参数
-c/--config
:指定配置文件-i/--input
:指定入口文件-o/--file
:指定输出文件-f/--format
:指定输出格式(amd, cjs, es, iife, umd, system)-w/--watch
:启用监听模式
输出控制
-d/--dir
:指定输出目录-m/--sourcemap
:生成sourcemap-n/--name
:UMD格式的全局变量名--compact
:压缩包装代码
模块处理
-e/--external
:排除指定模块-g/--globals
:指定全局变量映射--no-treeshake
:禁用tree-shaking
调试相关
--logLevel
:设置日志级别--perf
:显示性能计时--silent
:不打印警告
常见问题解决方案
获取当前目录路径
在ES模块中,替代__dirname
的方案:
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
const __dirname = dirname(fileURLToPath(import.meta.url));
导入package.json
不同Node版本的导入方式:
Node 18.20+:
import pkg from './package.json' with { type: 'json' };
旧版本Node:
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const pkg = require('./package.json');
最佳实践建议
- 优先使用配置文件:对于复杂项目,配置文件比命令行参数更易维护
- 合理使用TypeScript:利用类型提示减少配置错误
- 模块化配置:将大型配置拆分为多个文件,通过函数组合
- 环境区分:通过命令行参数实现开发/生产环境的不同配置
- 性能监控:在关键构建中使用
--perf
参数识别性能瓶颈
通过掌握这些Rollup命令行接口的知识,你将能够更高效地配置和使用Rollup,构建出更优化的JavaScript包。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考