【发布时间】:2016-06-01 13:03:34
【问题描述】:
我尝试使用 angular 2 创建一个应用程序,并希望在我的 .ts 文件中使用 underscore.js 库,例如当我想使用此功能时:
let myId = _.rest([5, 4, 3, 2, 1]);
_ 未定义并引发错误,我不想在我的模块中使用declare var _ : any;
【问题讨论】:
标签: angular typescript
我尝试使用 angular 2 创建一个应用程序,并希望在我的 .ts 文件中使用 underscore.js 库,例如当我想使用此功能时:
let myId = _.rest([5, 4, 3, 2, 1]);
_ 未定义并引发错误,我不想在我的模块中使用declare var _ : any;
【问题讨论】:
标签: angular typescript
对于基于https://cli.angular.io 的项目,我需要执行以下操作:
1) 导入库
npm install underscore --save
npm install @types/underscore --save
2) 在 tsconfig.app.json 中,给数组 'types' 添加下划线:
"types": [
"underscore"
]
3) 在我需要使用下划线的任何组件文件中,我添加这个
import * as _ from 'underscore';
4) 然后我可以使用:
console.log('now: ', _.now());
以及http://underscorejs.org的所有功能
【讨论】:
您必须为下划线添加 TypeScript 定义:
tsd 安装下划线
配置 SystemJS
System.config({
[...]
paths: {
underscore: './node_modules/underscore/underscore.js'
}
});
最后导入模块
import * as _ from 'underscore';
【讨论】:
检查这个回购。它有一个下划线的例子
https://github.com/angular/angular-cli/wiki/3rd-party-libs#adding-underscore-library-to-your-project
我在导入时这样做是为了让它发挥作用
//Place this at the top near your imports
/// <reference path="../../../../typings/globals/underscore/index.d.ts" />
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import * as _ from 'underscore';
确保您有正确的下划线参考路径。
【讨论】:
对于基于angular2-seed的项目,我需要:
安装下划线包:
npm install underscore --save
在 globalDependencies 下的 typings.json 中添加以下内容:
"underscore": "github:DefinitelyTyped/DefinitelyTyped/underscore",
在 project.config.ts 下添加以下内容:
this.SYSTEM_CONFIG_DEV.paths['underscore'] =
`${this.APP_BASE}node_modules/underscore`;
this.SYSTEM_BUILDER_CONFIG.packages['underscore'] = {
main: 'underscore.js',
defaultExtension: 'js'
};
在我的 ts 文件中导入“_”:
import * as _ from 'underscore';
【讨论】:
我已经使用这种方式为 Angular 4.0.2 包含了这个库:
npm install underscore --save
npm install @types/underscore --save
systemjs.config.js
map: {
// our app is within the app folder
'app': 'app',
.....
// other libraries
'rxjs': 'npm:rxjs',
'underscore': 'npm:/underscore/underscore.js'
}
最后:
import * as _ from 'underscore';
【讨论】:
您需要在项目中安装 underscore.d.ts 类型才能使用其 js 库。检查this 以了解如何包含类型
【讨论】: