webpack 3 零基础入门教程 #11 - 如何使用 pug (jade) 作为 HTML 的模板

1,058 阅读1分钟

首先肯定会问什么是 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

这样基本没啥问题,来看下结果:

我们来试试 puginclude 功能,就是可以包含子模板。

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

结果:

先这样吧。