ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 11. 如何使用 pug (jade) 作为 HTML 的模板 首先肯定会问什么是 [pug](https://github.com/pugjs/pug),如果是 nodejs 程序员的话,肯定听过 `jade` 吧,`pug` 就是 从 `jade` 改名过来的。 说白了,它就是可以让你以更好的语法来写 html 。 下面看看例子就会清楚的。 现在我们就要代替之前的 `src/index.html` 改用 pug 语法来写。 首先把 `src/index.html` 改名叫 `src/index.pug` ``` $ rename src/index.html src/index.pug ``` **src/index.pug** ``` doctype html html(lang="en") head title= pageTitle script(type='text/javascript'). if (foo) bar(1 + 5) body h1 Pug - node template engine #root #container.col if youAreUsingPug p You are amazing else p Get on it! p. Pug is a terse and simple templating language with a strong focus on performance and powerful features. ``` 上面的内容是从 `pug` 官方的示例中抄的,然后稍微改了一下。 **webpack.config.js** ``` ... module.exports = { ... plugins: [ ... new HtmlWebpackPlugin({ template: './src/index.pug', ... }), ... ], module: { rules: [ ... { test: /\.pug$/, loader: ['raw-loader', 'pug-html-loader'] } ] } }; ``` ``` $ npm install --save-dev pug pug-html-loader raw-loader ``` 这样基本没啥问题,来看下结果: ![](https://box.kancloud.cn/0e55b27f89ab9bc6f21d03bd04fa594f_961x324.png) 我们来试试 `pug` 的 `include` 功能,就是可以包含子模板。 **src/index.pug** ``` ... body include includes/header.pug ... ``` **src/includes/header.png** ``` h1 from header pug file ``` 目录结构是这样的: ``` src ├── Root.js ├── app.js ├── app.scss ├── contact.html ├── contact.js ├── includes │ └── header.pug └── index.pug ``` 结果: ![](https://box.kancloud.cn/a6133bf0697019fdfba3fbae28203701_1089x364.png) 先这样吧。