@rollup/plugin-html 使用及原理介绍
一款用于自动创建 html 文件并导入 rollup 打包文件进行展示的插件。
安装
npm install @rollup/plugin-html -D
使用
import html from '@rollup/plugin-html';
module.exports = {
input: 'index.js',
output: {
file: 'dist.js',
},
plugins: [html()]
};
在打包生成文件的同级目录中生成一个 index.html 文件,并自动引入打包文件。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Rollup Bundle</title>
</head>
<body>
<script src="dist.js" type="module"></script>
</body>
</html>
配置
attributes
Type: Object
Default: { html: { lang: 'en' }, link: null, script: null }
为 html、link、script 标签添加额外属性。
通过 key-value 的形式来添加标签属性,分别代表了 html 元素中的 属性名 和 值。
对于输出格式是 esm 的,会自动在 script 中添加 {type: ‘module’}属性。
fileName
Type: String
Default: 'index.html'
定义生成的 html 文件名。
meta
Type: Array[...object]
Default: [{ charset: 'utf-8' }]
用于定义 html 文件中 meta 元素的属性。
publicPath
Type: String
Default: ''
TODO 不确定
title
Type: String
Default: 'Rollup Bundle'
声明 html 文件的 title 值。
template
Type: Function
Default: internal function
Returns: String
用于自定义生成 html 文件。函数的格式如下:
const template = ({ attributes, bundle, files, publicPath, title }) => { ... }
- attributes:获取到传递给插件的参数
- bundle:包含 AssetInfo 或者 ChunkInfo 的对象。
- files:AssetInfo 或者 ChunkInfo 中 isEntry 为 true 的文件,及资源文件(isAsset: true) 的文件
- publicPath:传递的 publicPath 值。
- title: 传递的 title 值
默认的 html 模板是
<!DOCTYPE html>
<html ${attributes}>
<head>
${metas}
<title>${title}</title>
${links}
</head>
<body>
${scripts}
</body>
</html>
之后会根据传参自动填充上去。
支持输出的格式
该插件默认支持 esm
(es
), iife
, 和 umd
格式。如果是其他格式,可以在 template 配置中手动定义如何解析。
amd
使用 requireJS 语法,只允许一个 script 标签。如果导出多个文件,那么需要通过一个代理文件来导入。RequireJs 的使用需要手动引入一个依赖 https://requirejs.org/docs/start.html
system
首先需要一个独立的 script 标签,里边必须先包含了 s.js 这个加载器。之后才能使用:
<script>System.import('./batman.js')</script>
原理
在 generateBundle 钩子中调用 emitFile 生成一个 html 文件。
async generateBundle(output, bundle) {
...
const htmlFile: EmittedAsset = {
type: 'asset',
source,
name: 'Rollup HTML Asset',
fileName
};
this.emitFile(htmlFile);
}
模板生成:
const defaultTemplate = async ({
attributes,
files,
meta,
publicPath,
title
}: RollupHtmlTemplateOptions) => {
// 给入口文件生成 script 标签
const scripts = (files.js || [])
.map(({ fileName }) => {
const attrs = makeHtmlAttributes(attributes.script);
return `<script src="${publicPath}${fileName}"${attrs}></script>`;
})
.join('\n');
// 给入口资源文件生成 link 标签
const links = (files.css || [])
.map(({ fileName }) => {
const attrs = makeHtmlAttributes(attributes.link);
return `<link href="${publicPath}${fileName}" rel="stylesheet"${attrs}>`;
})
.join('\n');
// 生成 meta 标签
const metas = meta
.map((input) => {
const attrs = makeHtmlAttributes(input);
return `<meta${attrs}>`;
})
.join('\n');
return `
<!doctype html>
<html${makeHtmlAttributes(attributes.html)}>
<head>
${metas}
<title>${title}</title>
${links}
</head>
<body>
${scripts}
</body>
</html>`;
};