频道栏目
首页 > 资讯 > HTML/CSS > 正文

在Angular-cli中使用Pug(Jade)模板的步骤

17-12-21        来源:[db:作者]  
收藏   我要投稿

之前介绍过如何在Angular项目中使用Pug模板,但是方法不是很“优雅”,暴露了不必要的loader模块,且Pug模板编写方法与HTML不尽相同,部分属性需要引号包起来。

Angular实际是使用webpack进行打包的,那就可以直接修改webpack.config.js文件,添加pug文件的loader。

直接写步骤吧。

1 npm install pug-ng-html-loader --save-dev。

2 在项目的根目录下新建文件pug-rule-insert.js,内容为

const fs = require('fs');
const commonCliConfig = 'node_modules/@angular/cli/models/webpack-configs/common.js';
const pug_rule = `\n{ test: /.(pug|jade)$/, loader: "pug-ng-html-loader" },`;

fs.readFile(commonCliConfig, (err, data) => {
  if (err) { throw err; }

  const configText = data.toString(); 
  // make sure we don't add the rule if it already exists
  if (configText.indexOf(pug_rule) > -1) { return; }

  // We made it this far, let's insert that pug webpack rule
  const position = configText.indexOf('rules: [') + 8;
  const output = [configText.slice(0, position), pug_rule, configText.slice(position)].join('');
  const file = fs.openSync(commonCliConfig, 'r+');
  fs.writeFile(file, output); // ta-da
  fs.close(file);
});

这实际是修改了webpack打包文件。

3 执行node pug-rule-insert.js

4 修改templateUrl属性,比如改为’./my-component.template.pug’。

5 修改package.json文件,新增postintall钩子,这样每次install完成之后都会自动修改webpack配置文件

scripts:{
    ...
    "postinstall": "node pug-rule-insert.js"
}

6 执行ng serve查看效果

相关TAG标签
上一篇:博弈问题总集:Staircase Nim“编程题”
下一篇:关于PHP循环遍历数据库中表的字段并显示到前端的教程
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站