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

首先确定会问什么是 pug,若是是 nodejs 程序员的话,确定听过 jade 吧,pug 就是 从 jade 更名过来的。javascript

说白了,它就是能够让你以更好的语法来写 html 。css

下面看看例子就会清楚的。html

如今咱们就要代替以前的 src/index.html 改用 pug 语法来写。java

首先把 src/index.html 更名叫 src/index.pugnode

$ rename src/index.html src/index.pug
复制代码

src/index.pugwebpack

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 官方的示例中抄的,而后稍微改了一下。git

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
复制代码

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

咱们来试试 puginclude 功能,就是能够包含子模板。web

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
复制代码

结果:

先这样吧。

相关文章
相关标签/搜索