指令(Directive)
JavaScript 中有一种称为“指令”的机制,用于标注部分代码。
Rolldown 可能无法完整保留指令相关的语义,下面介绍 Rolldown 处理指令的策略。
"use strict"
"use strict" 指令用于告知 JavaScript 引擎强制使用严格模式。由于保留顶层 "use strict" 指令的语义较为复杂,并且会增大输出体积,Rolldown 可能不会保留它。
由于 ES 模块始终运行在严格模式下,当 output.format: 'es' 时,Rolldown 不会输出任何 "use strict" 指令。需要注意的是,这也意味着以 ES 模块格式输出时,原本不处于严格模式的代码会被强制置于严格模式。
可以通过 output.strict 选项控制是否生成 "use strict" 指令:
true:始终在输出顶部生成"use strict"(不适用于 ESM 格式,因为 ESM 始终处于严格模式)。false:永不在输出中生成"use strict"。'auto'(默认值):遵循源代码中的"use strict"指令。
ts
import { defineConfig } from 'rolldown';
export default defineConfig({
output: {
format: 'cjs',
strict: true,
},
});当 output.format 不是 'es' 且 output.strict 为 'auto' 时,Rolldown 会在以下任一情况下输出 "use strict" 指令:
- 指令不在顶层作用域中,且不在严格模式作用域内(REPL)。
- 指令位于顶层作用域中,且该模块是入口模块(REPL)。
- 指令位于顶层作用域中,且启用了
output.preserveModules(REPL)。
其他指令
ECMAScript 规范允许各实现定义额外指令。由于这些额外指令并非规范的一部分,Rolldown 无法得知它们的语义,只能假设它们遵循与 "use strict" 相似的语义。但出于上述同样的原因,Rolldown 可能不会保留顶层指令。
Rolldown 会在以下任一情况下输出指令:
如果希望向所有文件添加自定义指令,可以使用 output.banner 选项:
ts
import { defineConfig } from 'rolldown';
export default defineConfig({
output: {
banner: "'use client';",
},
});