关于Pug模板引擎,之前的名字叫Jade,关于它的介绍:可以参考这里,它是一个
Pug – robust, elegant, feature rich template engine for Node.js
。这里还有一个关于JS模板引擎的常用的几个:JS template engines。
先安装:
安装完成后,它的当前最新版本是:
"pug-html-loader": "^1.1.5",
将之前的my-index.html模板改成:my-index.pug,并把内容改成github上的demo:
doctype html
html(hljs-string">"en")
head
title= pageTitle
script(type='text/javascript').
if (foo) bar( + )
body
h1 Pug - node template engine
#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.
需要在webpack.config.js的modules对象中再新加一条rule:
{
test: /\.pug$/,
use: 'pug-html-loader'
}
同时把plugins对象中的用到my-index.html的HtmlWebpackPlugin中的template,也要改成my-index.pug:
new HtmlWebpackPlugin({
title: 'webpack',
excludeChunks:['anotherPage'],
hash: true,
template: './src/my-index.pug', // Load a custom template (lodash by default see the FAQ for details)
})
当去重新build的时候,出现了问题,编译失败:
ERROR in Error: Child compilation failed:
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <!DOCTYPE html><html lang="en"><head><title></title><script type="text/javascript">if (foo) bar( + )</script></hea d><body><h1>Pug - node template engine</h1><div class="col" id="container"><p>Get on it!</p><p>Pug is a terse and simp le templating language with a
| strong focus on performance and powerful features.</p></div></body></html>:
SyntaxError: Unexpected token (1:0)
看它的log,可以看到是因为缺少合适的loader,目前只安装了并使用了pug-html-loader,解决办法是还是需要安装html-loader,这里有很多loaders:
安装好后的当前版本是:
然后把这个loader加到webpack.config.js的modules对象中的rule中:
{
test: /\.pug$/,
use: ['html-loader','pug-html-loader']
}
再去build后,就会成功了:
现在我们可以给my-index.pug模板中再嵌套一些其他模板,在src目录下面新建一个新的目录includes,并在该目录下新建一个header.pug文件,文件中内容:
h1 this is the pug template header
那么现在只需要把这个header.png 包含进去就可以了:
doctype html
html(hljs-string">"en")
head
title= pageTitle
script(type='text/javascript').
if (foo) bar( + )
body
include includes/header.pug
h1 Pug - node template engine
#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.
重新build后,就可以看到了刚嵌套进去的header:
这样的话,根据项目需要可以把一个homepage分成n个template,最后再组合到一起,在实际的开发中也用的比较多。