【问题标题】:angular2: Cannot find module '@angular/core'angular2:找不到模块'@angular/core'
【发布时间】:2016-09-25 20:24:22
【问题描述】:

我按照 angular2 quick start 创建了我的项目,一切正常,但我的“tsc -w”命令行不断告诉我:

app/components/company/company.ts(1,36): error TS2307: Cannot find module '@angular/core'.
app/components/company/company.ts(5,22): error TS2307: Cannot find module '@angular/router'.
app/components/mission/mission.ts(1,36): error TS2307: Cannot find module '@angular/core'.
app/components/mission/mission.ts(3,22): error TS2307: Cannot find module '@angular/router'.

还有很多其他这样的行。然而,一切都编译成功,我的应用程序工作正常,但是将所有这些警告/错误作为真正的错误,在它们中间丢失了东西,这很烦人。

我正在使用 Angular2 rc1、TypeScript 1.8.10、WebStorm EAP(虽然我没有使用 WebStorm TypeScript 编译系统,但我使用的是带有“tsc -w”命令行的开放终端)。

我在 SO 上查看了与此相关的其他问题,但没有发现任何真正帮助我的东西。

更新

这是我的 tsconfig.json 文件:

{
  "compilerOptions": {
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "system",
    "noImplicitAny": false,
    "outDir": "js",
    "rootDir": "app"
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

【问题讨论】:

  • 嗯...显然,自从我创建项目以来,这个文件已经在快速启动中发生了变化。在我的打字中,我只有“es6-shim”、“jasmine”和“node”。但是,我现在看到,在快速入门中,“es6-shim”被“core-js”取代,但我觉得它不能解决我的问题(我错了吗?)。此外,“Thierry Templier”提出的解决方案是可行的。谢谢

标签: typescript angular


【解决方案1】:

您应该将moduleResolution 属性用于node

{
  "compilerOptions": {
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "system",
    "moduleResolution": "node", // <-----
    "noImplicitAny": false,
    "outDir": "js",
    "rootDir": "app"
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

【讨论】:

  • 确实看起来好多了。你能用两个词解释一下它有什么变化吗?
  • 这是编译器查找库合约的d.ts 文件的方式。看到这个问题:stackoverflow.com/questions/37413533/….
  • 不知何故我的编辑器仍然有Cannot find module '@angular/core',即使这是在src/ tsconfig 中?
【解决方案2】:

您首先需要在全局级别添加类型,如下所示。

npm install -g typings

然后使用以下命令创建 typings.json。

typings init

将下面的代码粘贴到typings.json中

{
  "name": "ng2-application",
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}

现在您需要在 tsconfig.json 中添加以下代码

 "compilerOptions": {
        "moduleResolution": "node"
       }

完成上述步骤后,您将能够在 F12 上获得定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2018-07-01
    相关资源
    最近更新 更多