兼容性垫片
robuild 提供 CJS/ESM 互操作的兼容性垫片,解决模块格式之间的差异。
启用垫片
CLI
sh
robuild --shims ./src/index.ts1
配置文件
build.config.ts
ts
import { defineConfig } from 'robuild'
export default defineConfig({
entries: [
{
type: 'bundle',
input: './src/index.ts',
shims: true,
},
],
})1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
垫片内容
启用 shims 后,会自动注入以下兼容代码:
ESM 输出中的 CJS 变量
在 ESM 输出中提供 __dirname 和 __filename:
js
import { fileURLToPath } from 'node:url'
import { dirname } from 'node:path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)1
2
3
4
2
3
4
ESM 输出中的 require
在 ESM 输出中提供 require 函数:
js
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)1
2
2
精细控制
使用对象配置精确控制需要哪些垫片:
build.config.ts
ts
import { defineConfig } from 'robuild'
export default defineConfig({
entries: [
{
type: 'bundle',
input: './src/index.ts',
shims: {
dirname: true, // __dirname 和 __filename
require: true, // require() 函数
exports: true, // module.exports
env: false, // process.env(浏览器)
},
},
],
})1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
使用场景
- 将 CJS 库迁移到 ESM
- 在 ESM 中使用依赖
__dirname的库 - 创建同时兼容 CJS 和 ESM 的包
WARNING
垫片会增加输出体积。只在确实需要时启用。
