刚开始使用 Angular 2,我遇到了最奇怪的问题。我从 GitHub 的 Angular 2 Quickstart 存储库开始,并添加了一些带有模板的组件。
例如:
import { Component } from '@angular/core';
import { LayoutComponent } from './layout.component';
@Component({
selector: 'app',
template: `<layout></layout>`,
})
export class AppComponent { name = 'Angular'; }
编译后的 TS(生成的 JS 文件)如下所示:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var AppComponent = (function () {
function AppComponent() {
this.name = 'Angular';
}
AppComponent = __decorate([
core_1.Component({
selector: 'app',
template: "<layout></layout>",
}),
__metadata('design:paramtypes', [])
], AppComponent);
return AppComponent;
}());
exports.AppComponent = AppComponent;
//# sourceMappingURL=app.component.js.map
如您所见,LayoutComponent 缺少 require 调用,当然,未找到 Layout 组件,因此布局标记不存在(这会导致浏览器中的运行时 JS 错误)。
我的所有组件都会发生这种情况,而不考虑路径(引用同一目录中的组件或当前目录下方/上方的组件)。
为什么 tsc 不包括这些进口?
最佳答案
import { LayoutComponent } from './layout.component';
这只是一个带有 ES6 模块语法的导入语句,与 Angular 或任何框架无关。
Tsc 在这里做的正是它应该做的。它通过删除未使用的符号来优化编译。
我相信您正在尝试实现嵌套组件。如果
AppComponent
是根组件,您可以简单地在 LayoutComponent
配置中将 declaration
添加到 @NgModule
,其中声明了根模块。@NgModule({
...
declarations: [
AppComponent,
LayoutComponent
]
})
尽管如此,最好有一个根组件,所以我会将
LayoutComponent
封装在一个 e.g. 中LayoutModule
并将它们添加到根模块@NgModule({
...
imports: [
LayoutModule
],
declarations: [
AppComponent,
]
})
这就是如何使
LayoutComponent
可用于 AppComponent
,如果您将组件/模块添加到根模块,则几乎可以在整个应用程序中使用。关于angular - 已编译的 TypeScript 中导入的组件缺少 Require 语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42794788/