主题
使用 CommonJS 模块
Rollup 力求实现 ES 模块的规范,而不是 Node.js、NPM、require() 和 CommonJS 的行为。因此,CommonJS 模块的加载和使用 Node 的模块位置解析逻辑都作为可选插件实现,不包含在 Rollup 核心中。
只需安装 commonjs
和 node-resolve
插件,然后使用 rollup.config.js
文件启用它们,即可完成设置:
js
const commonjs = require('@rollup/plugin-commonjs')
const nodeResolve = require('@rollup/plugin-node-resolve')
module.exports = {
// ...
plugins: [
// ...
commonjs(), // 将 CommonJS 模块转换为 ES6 模块
nodeResolve(), // 在 node_modules 中查找和捆绑第三方依赖项
],
}
提示
如果你的项目同时使用了 CommonJS
和 ESM
模块,使用这两个插件可以提高兼容性,并确保所有模块都能正确解析和打包。
如果模块导入 JSON 文件,则还需要 json
插件:
js
const json = require('@rollup/plugin-json')
module.exports = {
// ...
plugins: [
// ...
json(), // 将 .json 文件转换为 ES6 模块
],
}
如果模块导入 yaml 文件,则还需要 rollup-plugin-yaml
插件:
js
import yaml from '@rollup/plugin-yaml'
export default {
// ...
plugins: [
// ...
yaml(), // 将 .json 文件转换为 ES6 模块
],
}
如果打包一个 CIL 应用,则还需要 rollup-plugin-preserve-shebang
插件:
js
const shebang = require('rollup-plugin-preserve-shebang')
module.exports = {
// ...
plugins: [
// ...
shebang(), // 保留 #!/usr/bin/env node
],
}