6

免责声明:是的,我看到有更多“为组件 AppComponent 指定的模板不是字符串”相关问题,但没有一个描述我遇到的具体问题。

当我在ng build中不使用 AoT 进行编译时出现此运行时错误:

Uncaught Error: The template specified for component AppComponent is not a string

这个错误实际上是有道理的,因为在生成的捆绑代码(main.ts)中我看到:

template: __webpack_require__(/*! raw-loader!./app.component.html */ "../node_modules/raw-loader/dist/cjs.js!../Scripts/app/app.component.html"),

在一个新的 Angular 应用程序中,我看到:

template: __webpack_require__(/*! ./app.component.html */ "./src/app/app.component.html")

不知何故,原始加载器作为加载器添加到我的 .html 文件中。

现在也许重要的是要提到我正在将我的 webpack 4 AngularJs 项目迁移到 Angular 8。但是当我调试我的 webpack 构建时,我看不到它的测试包含.html加载器的规则。包含raw-loader

loader规则调试图

所以我的加载器规则不会影响这个原始加载器添加到 app.component.html

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
}

app.component.html:

 <div></div>

我会很感激任何帮助,谢谢。

4

4 回答 4

6

将raw-loader从 2.0.0降级到1.0.0解决了这个问题。

首先,我从 Angular 源代码中了解到,他们从 Angular 8 开始默认在此处将 raw-loader 添加到 templateUrl 。然后在此处使用它。

raw-loader 2.0.0 生成:

/***/ "../node_modules/raw-loader/dist/cjs.js!../Scripts/app/app.component.html":
/*!********************************************************************************!*\
  !*** ../node_modules/raw-loader/dist/cjs.js!../Scripts/app/app.component.html ***!
  \********************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ("<div>\r\n    app componenets works!\r\n</div>\r\n");

/***/ }),

raw-loader 1.0.0 生成:

    /***/ "../node_modules/raw-loader/index.js!../Scripts/app/app.component.html":
/*!********************************************************************!*\
  !*** ../node_modules/raw-loader!../Scripts/app/app.component.html ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = "<div>\r\n    app componenets works!\r\n</div>\r\n"

/***/ }),

这很好。Angular 需要 module.exports 在这里是字符串。

于 2019-07-18T08:59:53.237 回答
1

确保您正在使用

  templateUrl: './app.component.html', // or whatever filename

代替 template: './app.component.html',

于 2019-07-17T14:36:06.623 回答
0

曾经是

templateUrl: 需要('./app.component.html').default

..raw-loader > 1 ,因为默认导出。

于 2019-07-24T01:28:27.607 回答
0

组件 AppComponent 的模板出现错误。

在完成 npm 安装后,首先关闭浏览器,然后在该类型 ( npm i ) 进入终端后重新打开它。然后输入( ng serve )。

于 2021-12-21T19:02:34.777 回答