我正在 Ionic2/Angular2 typescript 项目中使用图形库 C3
。我通过 npm
安装了 C3
,通过 tsd
安装了类型定义。
我已经将 when 导入到我自己的 ts 文件中,如下所示。
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import * as C3 from 'c3';
import * as D3 from 'd3';
@Component({
templateUrl: 'build/pages/graphs-page/graphs-page.html'
....
})
一切都很好。我可以看到 C3(和相关 D3)的类型,而且当我运行时一切似乎都正常。
但是,当应用程序构建时(当我运行 ionic serve
时),我总是会遇到以下 typescript 编译错误...
TypeScript error: D:/dev/ionic2/testcomonents/app/pages/graphs-page/graphs-page.ts(3,21): Error TS2307: Cannot find module 'c3'.
TypeScript error: D:/dev/ionic2/testcomonents/app/pages/graphs-page/graphs-page.ts(4,21): Error TS2307: Cannot find module 'd3'.
有没有人知道为什么我在构建时会收到这些错误,而我在 IDE 中没有收到任何错误(我正在使用 vscode
),而且一切似乎都运行良好?
[编辑]
我已经安装了 typescipt 2 并使用 --traceResolution
标志运行。我可以看到 tsc
似乎只查看 node_modules
的各个级别,而从不查看 typings
文件夹,这是 vscode
正在寻找。
(对我来说)更令人困惑的是 c3.js 源代码是如何包含的,当它位于 node_modules/c3 文件夹下时。我没有特别添加对 c3.js
的任何引用,但图表显示出来了。
tsconfig.json
中的设置是
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"filesGlob": [
"**/*.ts",
"!node_modules/**/*"
],
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
],
"compileOnSave": false,
"atom": {
"rewriteTsconfig": false
}
}
我在上面的 tsconfig.json
中尝试了各种编辑,但无法在 typings 文件夹中查看它。
所以我的问题现在变成了
- 如何在 typings 文件夹中显示 Typscript
- 位于 node_modules\c3\c3.js 的实际 c3.js 文件如何包含在 Ionic 包中(因为我没有在任何地方添加对它的引用)
最佳答案
我想我现在知道这个问题的答案了,但如果我不正确,请纠正我!
查看Ionic文件D:\dev\ionic2\testcomponents\node_modules\ionic-gulp-browserify-typescript\index.js
,有如下src属性
var defaultOptions = {
watch: false,
src: ['./app/app.ts', './typings/main.d.ts'],
所以如果我将以下内容添加到 main.d.ts
/// <reference path="globals/c3/index.d.ts" />
/// <reference path="globals/d3/index.d.ts" />
错误消失了。
如果我运行 tsc --traceResolution
我仍然会看到错误,但我的猜测是从命令行运行 tsc
不包括查看上面的 Ionic 脚本或 main.d.ts
。
为了消除使用 tsc --traceResolution
时的错误,我尝试将以下内容添加到文件 D:\dev\ionic2\testcomponents\node_modules\c3\package.json
"typings": "../../typings/globals/c3/index.d.ts",
然后为 d3
做同样的事情。但这会在我运行 Ionic 构建时导致以下错误
TypeScript error: d:/dev/ionic2/testcomponents/app/pages/graphs-page/graphs-page.ts(3,21): Error TS2656: Exported external package
typings file 'd:/dev/ionic2/testcomponents/typings/globals/c3/index.d.ts' is not a module. Please contact the package author to update the package definition.
因此,我认为在 Ionic 上下文中,正确的做法是将 ///
路径添加到 main.d.ts 文件。
我遇到的另一个问题,即 c3.js 等文件是如何包含的,这是 Browserfity/gulp 构建的所有部分,它会检查 nodes_modules 文件夹下的所有内容。它们都有 packeage.json
文件,对于 c3,我们有 "main": "c3.js"
行。
关于angularjs - 导入 C3 和 D3 时出现 Typescript 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38550228/