TS2307:在 TypeScript 上导入 Angular2 时找不到模块“angular2/core”

TS2307: Cannot find module 'angular2/core' while importing Angular2 on TypeScript

本文关键字:模块 angular2 core 找不到 TypeScript Angular2 导入 TS2307      更新时间:2023-09-26
嗨,我

有一点 Angular 1 的背景,我正在学习 Angular 2。

对于从 Angular 1 开始,唯一的依赖关系是添加角度源angular.jsangular.min.js

当通过脚本标签尝试使用 Angular 2 时,

<script src="angular2.js"></script>

我收到这样的错误,

  • Uncaught ReferenceError: System is not defined
  • Uncaught ReferenceError: define is not defined

所以我搜索了SE并发现,在加载angular2之前必须添加system.jsrequire.js

无论如何我设法加载这两个库,

我喜欢编译 TypeScript 并提供js文件,而不是将所有脚本发送到客户端并编译/转译客户端的所有内容。

我的IDE是WebStorm,当我尝试编写一个简单的组件时,

import {Component} from 'angular2/core';
@Component
class Hello{
    name:string;
    constructor() {
        this.name = "HelloWorld";
    }
}

我在 main.ts 上的 TypeScript 编译器上收到此错误,该编译器编译为 main.js

Error:(1, 25) TS2307: Cannot find module 'angular2/core'.

TypeScript 编译所有内容,但不是从 angular 导入的。

我的简单index.html如下所示,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
</head>
<body>
    <script src="system.js"></script>
    <script src="require.js"></script>
    <script src="angular2.js"></script>
    <script src="main.js"></script>
</body>
</html>

是什么原因导致 TypeScript 无法从 angualr2 导入模块? 我应该使用 Angular2 配置 TypeScript 吗?

我是打字稿的新手,

非常感谢您的任何帮助

更新

TSC main.ts --watch 输出:

main.ts(1,25): error TS2307: Cannot find module 'angular2/core'.
main.ts(4,7): error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.
11:43:39 PM - Compilation complete. Watching for file changes.

因为你是 TypeScript 的新手。我仍然建议您按照 angular.io 文档启动 5 分钟。这有具体的说明,并且很好地解释了开始使用它。

Angular2 5 分钟快速入门页面 @ angular.io

你基本上需要什么才能开始:

  1. 节点.js带有 npm 包管理器。
  2. 带有编译器的打字稿。
  3. 文本编辑器或任何 IDE、VS Code
  4. 任何浏览器,如 Chrome

安装节点js,它还安装npm(节点包管理器)。现在,您需要按照以下步骤开始:

  1. 创建您选择的根文件夹名称,例如ng2Playground
  2. 现在您必须在其中再创建一个文件夹,该文件夹实际上包含所有.ts文件/组件文件,您可以将其命名app名称与文档相同
  3. 现在在根级别,您必须放置 4 个文件。
    3.1. tsconfig.json
    3.2 键入.json
    3.3 包.json
    3.4 索引.html
  4. 当您设置它时,由于我们尚未完成,但您可以npm start当我们完成加载所有依赖项时,运行此命令以开始编译并监视应用程序,同时开发其他组件。

现在,根据第 3 点,这些文件应该有什么。

3.1 : tsconfig.json:

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

3.2 : 键入.json

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2"
  }
}  

3.3 : 包.json

{
  "name": "ng2-test",
  "version": "1.0.0",
  "scripts": {
    "start": "concurrent '"npm run tsc:w'" '"npm run lite'" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.7",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.5.15"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.1.0",
    "typescript": "^1.7.5",
    "typings":"^0.6.8"
  }
}

一切顺利,恭喜!然而,我们需要最重要的文件index.html .

3.4 : 索引.html

<!doctype html>
<html>
<head>
  <title>Angular 2 QuickStart</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- 1. Load libraries -->
  <!-- IE required polyfills, in this exact order -->
  <script src="node_modules/es6-shim/es6-shim.min.js"></script>
  <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
  <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <script src="node_modules/rxjs/bundles/Rx.js"></script>
  <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
  <!-- 2. Configure SystemJS -->
  <script>
    System.config({
      packages: {
        app: {
          format: 'register',
          defaultExtension: 'js'
        }
      }
    });
    System.import('app/main')
      .then(null, console.error.bind(console));
  </script>
</head>
<!-- 3. Display the application -->
<body>
  <my-app>Loading...</my-app>
</body>
</html>

好!

我们的基本设置非常好,但我们需要安装所有依赖项和开发依赖项,这是绝对必需的。您需要运行npm install .这将安装我们在package.json中的所有依赖项。

软件包安装完成后,您可以找到一个名为node_modules的文件夹,该文件夹包含package.json中根据依赖项的所有文件。

如果在npm install时发生任何错误,则只需更新开发/依赖项。

因此,我假设您已经安装了所有依赖项,让我们开始:

现在根据第 2 点,我们有一个名为 app 的文件夹,现在我们将.ts文件放入其中。

创建一个名为 app.component.ts 的文件,请参阅命名约定.component.ts,其中表示它是一个组件文件。把这段代码放进去:

import {Component} from 'angular2/core'; // <-- importing Component from core
@Component({
    selector: 'my-app', //<----the element defined in the index.html
    template: '<h1>My First Angular 2 App</h1>' // <---this is the template to put in the component.
})
export class AppComponent { } // <--- we need to export the class AppComponent.  

现在创建另一个名为 main.ts 的文件。为什么main.ts?这是因为index.html,我们已经定义了我们的Systemjs模块加载器,请参阅index.html

System.import('app/main')

main.ts的内容:

import {bootstrap}    from 'angular2/platform/browser' // import bootstrap
import {AppComponent} from './app.component' // import the component we just created
bootstrap(AppComponent); // finally bootstrap it.  

现在我们完成了。

耶!!!

然而,我们需要运行它,为此我们必须cd ng2Playgroud它。 我们需要从命令提示符运行以下命令,或者如果您安装了 git bash,请运行以下命令:

npm start  

并按回车键。现在,它将编译并启动作为依赖项安装的lite-server。如果一切顺利,那么您会看到模板My First Angular 2 App浏览器中呈现。

我能够通过在我的tsconfig.json文件中添加"moduleResolution":"node"来解决此问题

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

首先回答这个问题,是什么导致TypeScript不从angualr2导入模块?我应该用Angular2配置TypeScript吗?您已导入模块加载程序,但尚未对其进行配置。您不必使用 Angular2 配置 TypeScript,而不必使用 Module loader 来配置。

由于接受的答案已经过时(针对 Angular2 的测试版),

很多事情都发生了变化,包括当前 Angular 2 (RC2) 候选版本中的模块加载器,这对我有用,

目录结构。

.                             # project directory
├── app                       # main app directory
│   ├── app.component.ts
│   └── main.ts
├── bs-config.js             
├── index.html
├── node_modules              # npm package directory
├── package.json
├── styles.css
├── systemjs.config.js
├── tsconfig.json
└── typings.json

文件是。

应用

:项目文件所在的应用目录。
app.component.ts:应用组件文件
main.ts:入口点和引导程序
bs-config.js:精简服务器(基于浏览器同步的开发服务器)配置
索引.html:应用程序的
索引页node_modules:npm 包的安装
位置package.json:npm 配置文件
systemjs.config.js:SystemJS 配置
tsconfig.json:TypeScript Compiler 配置
typings.json:类型定义

每个文件的内容。

  1. index.html文件

    <html>
      <head>
        <title>Hello Angular 2</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">
        <!-- 1. Load libraries -->
         <!-- Polyfill(s) for older browsers -->
        <script src="node_modules/core-js/client/shim.min.js"></script>
        <script src="node_modules/zone.js/dist/zone.js"></script>
        <script src="node_modules/reflect-metadata/Reflect.js"></script>
        <script src="node_modules/systemjs/dist/system.src.js"></script>
        <!-- 2. Configure SystemJS -->
        <script src="systemjs.config.js"></script>
        <script>
          System.import('app').catch(function(err){ console.error(err); });
        </script>
      </head>
      <!-- 3. Display the application -->
      <body>
        <my-app>Loading...</my-app>
      </body>
    </html>
    
  2. package.json

    {
        "name": "hello-angular-2",
        "version": "1.0.0",
        "scripts": {
          "start": "tsc && concurrently '"npm run tsc:w'" '"npm run lite'" ",
          "lite": "lite-server",
          "postinstall": "typings install",
          "tsc": "tsc",
          "tsc:w": "tsc -w",
          "typings": "typings"
        },
        "license": "ISC",
        "dependencies": {
          "@angular/common":  "2.0.0-rc.2",
          "@angular/compiler":  "2.0.0-rc.2",
          "@angular/core":  "2.0.0-rc.2",
          "@angular/http":  "2.0.0-rc.2",
          "@angular/platform-browser":  "2.0.0-rc.2",
          "@angular/platform-browser-dynamic":  "2.0.0-rc.2",
          "@angular/router":  "2.0.0-rc.2",
          "@angular/router-deprecated":  "2.0.0-rc.2",
          "@angular/upgrade":  "2.0.0-rc.2",
          "systemjs": "0.19.27",
          "core-js": "^2.4.0",
          "reflect-metadata": "^0.1.3",
          "rxjs": "5.0.0-beta.6",
          "zone.js": "^0.6.12",
          "angular2-in-memory-web-api": "0.0.12",
          "bootstrap": "^3.3.6"
        },
        "devDependencies": {
          "concurrently": "^2.0.0",
          "lite-server": "^2.2.0",
          "typescript": "^1.8.10",
          "typings":"^1.0.4"
        }
      }
    
  3. systemjs.config.js

    /**
     * System configuration for Angular 2 samples
     * Adjust as necessary for your application needs.
     */
    (function(global) {
      // map tells the System loader where to look for things
      var map = {
        'app':                        'app', // 'dist',
        '@angular':                   'node_modules/@angular',
        'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
        'rxjs':                       'node_modules/rxjs'
      };
      // packages tells the System loader how to load when no filename and/or no extension
      var packages = {
        'app':                        { main: 'main.js',  defaultExtension: 'js' },
        'rxjs':                       { defaultExtension: 'js' },
        'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
      };
      var ngPackageNames = [
        'common',
        'compiler',
        'core',
        'http',
        'platform-browser',
        'platform-browser-dynamic',
        'router',
        'router-deprecated',
        'upgrade',
      ];
      // Individual files (~300 requests):
      function packIndex(pkgName) {
        packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
      }
      // Bundled (~40 requests):
      function packUmd(pkgName) {
        packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
      }
      // Most environments should use UMD; some (Karma) need the individual index files
      var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
      // Add package entries for angular packages
      ngPackageNames.forEach(setPackageConfig);
      var config = {
        map: map,
        packages: packages
      };
      System.config(config);
    })(this);
    
  4. tsconfig.json

    {
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
      }
    }
    
  5. typings.json

    {
      "globalDependencies": {
        "core-js": "registry:dt/core-js#0.0.0+20160317120654",
        "jasmine": "registry:dt/jasmine#2.2.0+20160505161446",
        "node": "registry:dt/node#4.0.0+20160509154515"
      }
    }
    
  6. main.ts

    import { bootstrap }    from '@angular/platform-browser-dynamic';
    import { AppComponent } from './app.component';
    bootstrap(AppComponent);
    
  7. app.component.ts

    import { Component } from '@angular/core';
    @Component({
      selector: 'my-app',
      template: '<h1>Hello World from Angular 2</h1>'
    })
    export class AppComponent { }
    


安装依赖项

保存上述所有文件后,在项目位置的终端窗口上运行npm install,这会将所有依赖项安装到node_modules目录中,这可能需要一些时间,具体取决于您的连接速度。

运行开发服务器

安装所有依赖项后,在项目位置的终端上运行npm start。这将同时运行打字稿编译器精简服务器,这有助于编译/转译代码并在您更改源代码时重新加载网页。

现在可能会打开一个新的浏览器窗口。如果没有,请将您最喜欢的浏览器指向 **http://127.0.0.1:3000/**http://localhost:3000/ ,如果一切顺利,您将看到一个页面,上面写着:

来自Angular 2的Hello World

就是这样!.


如果您不希望精简服务器在您每次运行npm start时自动打开浏览器,请将以下内容添加到您的bs-config.js中。

module.exports = {
    "open": false
};

来自 angular.io 的代码示例

使用 '@angular/core' 代替'angular2/core'<</p>

div class="answers">

在 index.html 中执行此操作:

<html>
<head>
    <base href="/"></base>
</head>
<body>
    <app>Loading....</app>
</body>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script>
    System.config({
                defaultJSExtensions: true
            });
</script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>    
<script>
    System.import('App');
</script>
</html>

尝试使用它您的第一个组件:

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
@Component({
    selector: 'app',
    template: "Hello"
})
export class App{  
    constructor(){ }    
}
bootstrap(App); 

您的索引.html文件缺少很多。 就像使用系统导入主组件一样.js即System.import('App');

tsconfig.json:

{
  "version": "1.5.3",
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "noImplicitAny": false
  }
}

您应该导入这些文件:

<!-- ZonesJS and Reflect-metadata -->
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<!-- SystemJS -->
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- RxJS (observables) -->
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<!-- Main Angular2 bundle -->
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>

并将此配置用于 SystemJS:

<script>
  System.config({
    defaultJSExtensions: true,
    packages: {
      app: {
        defaultExtension: 'js',
        format: 'register'
      }
    }
  });
  System.import('app/boot')
    .then(null, console.error.bind(console));
</script>

我假设您的 TypeScript 文件位于 app 子文件夹中,app/boot.ts是包含对 bootstrap 函数调用的文件夹。

确保文件夹"node_modules"(单击显示隐藏文件)位于正确的位置(在项目的根目录中,与 wwwroot 同级)。还要检查项目依赖项文件夹中显示@angular:

[项目名称]/依赖/npm/@angular...

当我将快速入门指南集成到新的 ASP.NET Core 项目中时,我正在移动文件,node_modules文件夹放错了位置。

希望这有帮助

你可能

忘了运行:

npm install

在您的角度项目下/