且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Pug 支持 Angular 2/Angular 4/Angular 6/Angular cli/Angular cli 6(无自定义 WebPack 配置)

更新时间:2023-09-30 10:40:40

我看到了很多解决方案,其中一些:

I saw many solutions, some of them:

  1. 在每个组件中添加了类似require!pug-loader()some.component.pug"

远离使用 angular-cli 并在 webpack 周围创造魔法

Get away from using angular-cli and create magic around webpack

使用其他服务器(知道如何使用 Pug/Jade)

Use other servers (who know how to work with the Pug / Jade)

在运行构建之前,将所有 pug 文件转换为 html

Before running the build, convert all the pug files to html

我认为他们会拒绝为 angular 辩护的服务器——这不是真的,只要你拒绝 angular-cli 并使用,就运行一些预编译器(它会创建文件并将它们发送给未来webpack - 出现错误(因为 angular 编译的不是有效的 webpack 文件)

I think that they will refuse the server justified for angular - it's not true, run some pre-compilers (which create files and send them to the gee in the future), as soon as you refuse the angular-cli and use webpack - errors appear (because the angular compiles not a valid webpack file)

我是这样决定的:

npm install pug pug-loader --save-dev

第一步后添加行到 package.json

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

然后使用以下内容创建文件 pug-rule-insert.js:

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

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

  const configText = data.toString();
  if (configText.indexOf(pug_rule) > -1) { return; }

  const position = configText.indexOf('rules: [') + 8;
  const output = [configText.slice(0, position), pug_rule, configText.slice(position)].join('');
  let file = fs.openSync(commonCliConfig, 'r+');
  fs.writeFile(file, output, () => {});
  fs.close(file, () => {});
});

针对 Angular 6 的修复:

const commonCliConfig = 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/common.js';

现在只需在终端中输入:

npm run afterInstall

该脚本放在您的主 WebPack 文件(位于 node_modules/angular/cli/models/webpack-config/common.js)行中,告诉 angular support pug

That script put in your main WebPack file (located at node_modules/angular/cli/models/webpack-config/common.js) row, that told angular support pug

Angular 团队默认没有将其包含在支持中,因为这是必要的:

the Angular team did not include it in support by default, because it is necessary:

  1. 所有指令、事件(如点击)应该分开","

示例:p((click)='someFunction()', [title]='myTitle')

不能使用 mixin(用 ng-template & ng-container 替换)

It is not possible to use a mixin (replace it with ng-template & ng-container)

这也很神奇,但 angular-cli 工作正常,所有测试工作,AoT &JiT - 工作

this is magic too, but angular-cli work fine, all test works, AoT & JiT - work