如何在angular 2中使用underscore.js库

Ali*_*ade 28 typescript angular

我尝试使用angular 2创建一个应用程序,并希望在我的.ts文件中使用underscore.js库,例如当我想要使用此函数时:

   let myId = _.rest([5, 4, 3, 2, 1]);
Run Code Online (Sandbox Code Playgroud)

_是没有定义和抛出错误,我不想 declare var _ : any;在我的模块中使用

小智 81

对于基于https://cli.angular.io的项目,我需要执行以下操作:

1)导入库

npm install underscore --save
npm install @types/underscore --save
Run Code Online (Sandbox Code Playgroud)

2)在tsconfig.app.json中,向数组'types'添加下划线:

"types": [
  "underscore"
]
Run Code Online (Sandbox Code Playgroud)

3)在任何组件文件中我需要使用下划线,我添加它

import * as _ from 'underscore';
Run Code Online (Sandbox Code Playgroud)

4)然后我可以使用:

console.log('now: ', _.now());
Run Code Online (Sandbox Code Playgroud)

以及http://underscorejs.org的所有功能

  • 为Ionic 3项目工作。只是跳过了第2步,就可以了。 (2认同)

Die*_*nue 21

您必须为Underscore添加TypeScript定义:

tsd安装下划线

配置SystemJS

System.config({
  [...]
  paths: {
    underscore: './node_modules/underscore/underscore.js'
  }
});
Run Code Online (Sandbox Code Playgroud)

最后导入模块

import * as _ from 'underscore';
Run Code Online (Sandbox Code Playgroud)


kab*_*ius 5

检查这个回购.它有一个下划线的例子

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';
Run Code Online (Sandbox Code Playgroud)

确保您有正确的参考路径指向下划线.


Vil*_*kas 5

对于基于angular2-seed的项目,我需要:

  1. 安装下划线包:

    npm install underscore --save
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在globalDependencies下的typings.json中添加以下内容:

    "underscore": "github:DefinitelyTyped/DefinitelyTyped/underscore",
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在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'
    };
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在我的ts文件中导入"_":

    import * as _ from 'underscore';
    
    Run Code Online (Sandbox Code Playgroud)