我有一个带有 typescript 的 angular2 应用程序示例,但我的项目中没有所有 node_modules ( like this )。必要的文件嵌入在我的 index.html
( as described in example 1 here ) 的 head
中:
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.0/es6-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.16/system-polyfills.js"></script>
<script src="https://npmcdn.com/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.13/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.13/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.13/angular2.dev.js"></script>
因为我想预编译我的 typescript 文件,所以我安装了 node.js
和 tsc
。我的编辑器 (PHPStorm 2016.1) 自动将文件编译为 assets/js
,如 tsconfig.json
中所定义:
{
"compilerOptions": {
"target": "es5",
"module": "system",
"declaration": true,
"noImplicitAny": false,
"preserveConstEnums": true,
"removeComments": true,
"outDir": "../assets/js",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"emitBOM": true,
"moduleResolution": "node"
}
}
应用程序加载 ( as described here ):
System.config({
packages: {
'assets/js': {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import( 'assets/js/main' ).then( null, console.error.bind( console ) );
在编译时,我总是会遇到(那种经典的)错误
error TS2307: Cannot find module 'angular2/core'
PHPStorm 告诉我它无法解析导入:
即使加载了所有外部库:
但在编译之后(即使出现上述错误)应用程序在浏览器中运行良好。
可能缺少 Typescript 定义 (TSD) ( link here ),但 tsd 已被弃用。我阅读了有关 typings install angular --ambient
的内容,但我不确定这是否真的有必要(并且它抛出了一堆其他错误 like this)。
所以我的问题:
这只是我可以忽略的设置(没有 node_modules)的副作用,还是我必须安装其他东西?
我的环境:
- Node 5.4.1
- npm 3.3.12
- tsc 1.8.9
- Mac OS X 10.11.4
- PHPStorm 2016.1
我有点迷茫。任何提示将不胜感激。
最佳答案
您遇到了问题,因为 TypeScript 编译器可以找到 Angular2 .d.ts
文件。它们在使用 NPM 安装 Angular2 时提供(请参阅文件夹 node_modules/angular2
下的文件 .d.ts
)。
在 tsconfig.json
文件中设置 module
属性时,编译器将尝试在 node_modules
文件夹中找到它们。
您会注意到在编译源代码时这是一个问题,但是此代码将被编译并且您的应用程序能够运行...
有类似 typings 和 tsd(已弃用)的工具可以手动安装此类类型,但相应的注册表中不存在 Angular2。
关于node.js - typescript 编译器错误 TS2307 : Cannot find module "angular2/core" when loading from CDN without NPM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36350361/