Angular2-Webpack-Typescript - 第 3 方库

Angular2-Webpack-Typescript - 3rd party libraries

我开始了一个美丽的种子项目:https://github.com/AngularClass/angular2-webpack-starter

我一直坚持使用第 3 方 modules.Can 有人 help/explain 如何正确 add/use 这个项目的外部模块?

例如,我添加 'immutable' 使用:

npm install immutable --save

之后,我试图 link 组件内的那个模块:

import * as immutable from 'immutable';
import {List} from 'immutable';
import Immutable = require('immutable');

没有任何帮助,它总是 returns TS2307:找不到模块“immutable”。例如,“moment”也是如此。

编辑:将以下内容添加到您的 main.ts 文件中。

import 'immutable'

这应该使您能够访问所有组件中的可推定 api,而无需任何额外的导入。

您需要将类型文件添加到位于 node_modules\immutable\dist\immutable.d.ts 的项目中。您需要在您的项目中引用它。它应该看起来像这样:

/// <reference path="node_modules/immutable/dist/immutable.d.ts" />
import * as immutable from 'immutable';
import {List} from 'immutable';
import Immutable = require('immutable');

暂时可以在 DefinitelyTyped. I recommend using tsd 上安装它们。

如果您遇到想要使用的库,但找不到任何类型,您可以查看 this question 以了解仍然可以使用它的简单方法。您只是不会获得任何 Typescript 的好处。

让我为使用第三方 (npm) javascript 模块的人提供一个可能的解决方法,该模块没有类型定义,并且想要摆脱 "cannot find module" 错误消息

假设您使用 npm 包 jsonapi-serializer 并在 example.ts 文件中引用它:

import {Serializer, Deserializer} from "jsonapi-serializer";

@Injectable()
export class ExampleService {
  var deserializer = new Deserializer({ keyForAttribute: 'camelCase'});
}

编译器会报错:Error:(1, 40) TS2307:Cannot find module 'jsonapi-serializer'.

您可以通过创建以下文件自行声明类型定义:jsonapi-serializer.d.ts。您必须指定主要功能,但使用 any 类型可以使其相对简单。 (如果创建完整定义,请考虑 donating 定义文件):

declare module 'jsonapi-serializer' {

    export class Serializer {
        constructor(type: string, ...options: any[]);
        serialize(arg: any)
    }

    export  class Deserializer {
        constructor(...options: any[]);
        deserialize()
    }
}

如果将此文件放入项目中,编译器将识别该模块。如果这不起作用,您还可以通过将以下行放在文件顶部来从 ExampleService.ts 文件中引用它:

///<reference path="jsonapi-serializer.d.ts"/>