posthtml-modules: 编译期模块处理插件

1,047 阅读1分钟

简介

posthtml-modules 是为 PostHTML 提供的模块化处理插件。它将特定的标签看作模块导入语句,通过对 HTML 进行解析和编译将模块导入语句所在的部分替换成模块文件中的内容,同时支持向模块传入嵌套内容和数据。能够在编写静态 HTML 时提供类似模板组件的编译期模块能力,提高代码可阅读性和开发效率。

安装

npm i -D posthtml-modules

示例

<!-- index.html -->
<html>
<body>
  <module href="./module.html">
    title
  </module>
</body>
</html>
<!-- module.html -->
<header>
  <h1>
    Test <content></content>
  </h1>
</header>
const { readFileSync } = require('fs')
const posthtml = require('posthtml')
const options = { /* 具体的可选选项见下方 */ }

posthtml()
  .use(require('posthtml-modules')(options))
  .process(readFileSync('index.html', 'utf8'))
  .then((result) => result)
  });
<html>
 <body>
   <header>
     <h1>Test title</h1>
   </header>
  </body>
</html>

选项

root

类型: string
默认值: ./

查找模块时使用的根目录。

plugins

类型: array | function
默认值: []

对解析的模块需要应用的 PostHTML 插件。

如果提供的是函数,它将会被调用并传入模块的文件路径。

from

类型: string
默认值: ''

应用处理的根文件名,用于路径解析(建议总是提供这个选项)。

initial

类型: boolean
默认值: false

在模块处理完成后对根文件应用插件。

tag

类型: string
默认值: module

自定义用于导入模块的标签名。

attribute

类型: string
默认值: href

自定义用于导入模块时指定路径的属性名。

组件选项

locals

你可以通过使用 locals="" 属性来向模块传递数据。

必须为一个有效的 JSON 对象。

例子:

<!-- module.html -->
<p>The foo is {{ foo }} in this one.</p>
<content></content>
<!-- index.html -->
<module href="./module.html" locals='{"foo": "strong"}'>
  <p>Or so they say...</p>
</module>

结果

<p>The foo is strong in this one.</p>
<p>Or so they say...</p>