Module Types
A Note to Our Readers
While maintaining fidelity to the source material, this translation incorporates explanatory content and localized expressions, informed by the translator's domain expertise. These thoughtful additions aim to enhance readers' comprehension of the original text's core messages. For any inquiries about the content, we welcome you to engage in the discussion section or consult the source text for reference.
作为一个 web
打包工具,JavaScript
并非 Rolldown
中唯一具有 内置支持的文件类型。例如,Rolldown
可以直接处理 TypeScript
和 JSX
文件,在打包前将它们解析并转换为 JavaScript
。我们将这些在 Rolldown
中具有 一级支持 的文件类型称为模块类型(Module Types
)。
How module types affect users
终端用户通常不需要关心模块类型,因为 Rolldown
会 自动识别 并处理已知的模块类型。
默认情况下,Rolldown
根据 文件扩展名 确定模块的类型。然而,在某些情况下这可能不够充分。例如,想象一个包含 JSON
数据的文件,但其扩展名为 .data
。Rolldown
无法通过文件扩展名将其识别为 JSON
文件,因为扩展名不是 .json
。
在这种情况下,用户需要 明确 告诉 Rolldown
具有 .data
扩展名的文件应被视为 JSON
模块类型。这可以通过配置中的 moduleTypes
选项完成:
export default {
moduleTypes: {
'.data': 'json'
}
};
Module types and plugins
插件可以通过 load
钩子和 transform
钩子指定特定文件的 模块类型:
const myPlugin = {
load(id) {
if (id.endsWith('.data')) {
return {
code: '...',
moduleType: 'json'
};
}
}
};
模块类型的主要意义在于他为支持的类型提供了一个中心化的约定,使得需要在同一模块类型上操作的多个插件能够更容易地链式调用。
例如,@vitejs/plugin-vue
目前为 .vue
文件中的样式块创建虚拟 CSS
模块,并向虚拟模块的 ID
附加 ?lang=css
,使这些模块能被 Vue
插件识别为 CSS
。然而,这仅仅是 Vue
插件的约定 - 其他插件可能会忽略查询字符串,因此无法识别这种约定。
通过模块类型,@vitejs/plugin-vue
可以明确将虚拟 CSS
模块的模块类型指定为 css
,而其他插件(如 PostCSS
插件)可以处理这些 CSS
模块,而无需了解 Vue
插件。
另一个例子:为了添加对 .jsonc
文件的支持,插件可以简单地在 load
钩子中去除 .jsonc
文件的注释,并返回 moduleType: 'json'
,后续 Rolldown
就可以按照 json
的模式来解析这个模块。