在Angular2应用程序中找不到名称模块

8

我正在使用angular-cli运行我的typescript驱动的angular2应用程序。我定义了一个AppComponent,如下所示:

import { Component } from '@angular/core';
import { ServersListComponent } from './servers-list/servers-list.component';

@Component({
    moduleId: module.id,
    selector: 'app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css'],
    directives: []
})
export class AppComponent {

}

由于在这个问题的主题中,moduleId: module.id 在第一行中引发了错误,因此 angular-cli 无法编译此文件。

我的 tsconfig.json 文件如下所示:

{
    "compileOnSave": false,
    "compilerOptions": {
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "mapRoot": "",
        "module": "commonjs",
        "moduleResolution": "node",
        "noEmitOnError": true,
        "noImplicitAny": false,
        "outDir": "../dist/",
        "rootDir": ".",
        "sourceMap": true,
        "target": "es5",
        "inlineSources": true
    },
    "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts"
    ]
}

在使用angular-cli时,不需要moduleId: module.id - maxime1992
4个回答

1

1

2017年中更新

自从Angular迁移到使用webpack后,不再需要声明moduleId,因为webpack插件会自动处理(添加)最终捆绑包中的module.id

截至2017年3月13日,由于包含webpack,Angular已删除所有对moduleId的引用,因此现在已弃用。

我们向推荐的SystemJS配置中添加了一个新的SystemJS插件(systemjs-angular-loader.js)。该插件动态将templateUrl和styleUrls中的"component-relative"路径转换为"absolute paths",供您使用。

我们强烈建议您只编写组件相关的路径。这是这些文档中讨论的唯一URL形式。您不再需要编写@Component({ moduleId: module.id }),也不应该这样做。


1
要使用module.id,你的项目必须是一个commonjs模块,即在tsconfig.json文件中将module属性设置为commonjs。这是否符合要求:
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs", // <-----
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

我更新了我的问题。你可以看到我在里面有 module: commonjs - Marek M.

0
今天我在使用angular-cli创建一个特性文件夹中的第一个组件时遇到了同样的问题。正如Maxime所说,你可以不使用模块ID来解决这个问题。但是你必须使用相对路径来引用你的模板和样式,就像最初生成的app.component一样:
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接