关于javascript:将lodash导入angular2 + typescript应用程序

Importing lodash into angular2 + typescript application

我很难尝试导入lodash模块。我使用npm + gulp设置我的项目,并继续击中同一面墙。我尝试过常规的lodash,还有lodash-es。

lodash npm包:(包根文件夹中有一个index.js文件)

1
import * as _ from 'lodash';

结果是:

1
error TS2307: Cannot find module 'lodash'.

lodash-es npm包:(在lodash.js中有一个defaut导出我的包根文件夹)

1
import * as _ from 'lodash-es/lodash';

结果是:

1
error TS2307: Cannot find module 'lodash-es'.

gulp任务和webstorm都报告了同样的问题。

有趣的是,这不会返回错误:

1
import 'lodash-es/lodash';

......但当然没有"_"......

我的tsconfig.json文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
 "compilerOptions": {
   "target":"es5",
   "module":"system",
   "moduleResolution":"node",
   "sourceMap": true,
   "emitDecoratorMetadata": true,
   "experimentalDecorators": true,
   "removeComments": false,
   "noImplicitAny": false
  },
 "exclude": [
   "node_modules"
  ]
}

我的gulpfile.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    uglify = require('gulp-uglify'),
    sourcemaps = require('gulp-sourcemaps'),
    tsPath = 'app/**/*.ts';

gulp.task('ts', function () {
    var tscConfig = require('./tsconfig.json');

    gulp.src([tsPath])
        .pipe(sourcemaps.init())
        .pipe(ts(tscConfig.compilerOptions))
        .pipe(sourcemaps.write('./../js'));
});

gulp.task('watch', function() {
    gulp.watch([tsPath], ['ts']);
});

gulp.task('default', ['ts', 'watch']);

如果我理解正确,我的tsconfig中的moduleResolution:'node'应该将import语句指向node_modules文件夹,其中安装了lodash和lodash-es。我也尝试了许多不同的导入方式:绝对路径,相对路径,但似乎没有任何工作。有任何想法吗?

如果有必要,我可以提供一个小的zip文件来说明问题。


以下是如何使用Typescript 2.0:
(tsd和typings被弃用以支持以下内容):

1
2
3
4
$ npm install --save lodash

# This is the new bit here:
$ npm install --save-dev @types/lodash

然后,在.ts文件中:

或者:

1
import * as _ from"lodash";

或者(由@Naitik建议):

1
import _ from"lodash";

我不是肯定的不同之处。我们使用并优先考虑第一种语法。但是,有些人报告第一种语法对他们不起作用,而另一些人则评论说后一种语法与延迟加载的webpack模块不兼容。因人而异。

2017年2月27日编辑:

根据下面的@Koert,import * as _ from"lodash";是Typescript 2.2.1,lodash 4.17.4和@ types / lodash 4.14.53中唯一的工作语法。他说另一个建议的导入语法给出错误"没有默认导出"。


2016年9月26日更新:

正如@ Taytay的回答所说,我们现在可以使用以下方法,而不是几个月前使用的"打字"装置。

1
npm install --save @types/lodash

以下是一些支持该答案的其他参考资料:

  • https://www.npmjs.com/package/@types/lodash
  • NPM @types org包中的TypeScript类型

如果仍然使用打字装置,请参阅下面的评论(由其他人)关于''' - ''''和''' - 'global'''。

此外,在新的快速入门中,config不再位于index.html中;它现在在systemjs.config.ts中(如果使用SystemJS)。

原答案:

这在我的Mac上工作(按照快速启动安装Angular 2之后):

1
2
3
sudo npm install typings --global
npm install lodash --save
typings install lodash --ambient --save

您会发现受影响的各种文件,例如

  • /typings/main.d.ts
  • /typings.json
  • /package.json

Angular 2 Quickstart使用System.js,所以我在index.html的配置中添加了'map',如下所示:

1
2
3
4
5
6
7
8
9
10
11
System.config({
    packages: {
      app: {
        format: 'register',
        defaultExtension: 'js'
      }
    },
    map: {
      lodash: 'node_modules/lodash/lodash.js'
    }
  });

然后在我的.ts代码中,我能够做到:

1
2
3
import _ from 'lodash';

console.log('lodash version:', _.VERSION);

2016年年中编辑:

正如@tibbus提到的,在某些情况下,您需要:

1
import * as _ from 'lodash';

如果从angular2-seed开始,并且如果您不想每次都导入,则可以跳过映射并导入步骤,只需取消注释tools / config / project.config.ts中的lodash行。

为了让我的测试使用lodash,我还必须在karma.conf.js中的files数组中添加一行:

1
'node_modules/lodash/lodash.js',


步骤1:修改package.json文件以在依赖项中包含lodash。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 "dependencies": {
"@angular/common": "2.0.0-rc.1",
"@angular/compiler": "2.0.0-rc.1",
"@angular/core": "2.0.0-rc.1",
"@angular/http": "2.0.0-rc.1",
"@angular/platform-browser": "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router": "2.0.0-rc.1",
"@angular/router-deprecated": "2.0.0-rc.1",
"@angular/upgrade": "2.0.0-rc.1",
"systemjs":"0.19.27",
"es6-shim":"^0.35.0",
"reflect-metadata":"^0.1.3",
"rxjs":"5.0.0-beta.6",
"zone.js":"^0.6.12",
"lodash":"^4.12.0",
"angular2-in-memory-web-api":"0.0.7",
"bootstrap":"^3.3.6"  }

第2步:我在angular2应用程序中使用SystemJs模块加载器。所以我会修改systemjs.config.js文件来映射lodash。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
(function(global) {

// map tells the System loader where to look for things
var map = {
    'app':                        'app', // 'dist',
    'rxjs':                       'node_modules/rxjs',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    '@angular':                   'node_modules/@angular',
    'lodash':                    'node_modules/lodash'
};

// packages tells the System loader how to load when no filename and/or no extension
var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
    'lodash':                    {main:'index.js', defaultExtension:'js'}
};

var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
];

// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});

var config = {
    map: map,
    packages: packages
}

// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }

System.config(config);})(this);

第3步:现在进行npm安装

第4步:在文件中使用lodash。

1
2
import * as _ from 'lodash';
let firstIndexOfElement=_.findIndex(array,criteria);


首先要做的事情

npm install --save lodash

<5233>

加载完整的lodash库

1
2
3
4
5
//some_module_file.ts
// Load the full library...
import * as _ from 'lodash'
// work with whatever lodash functions we want
_.debounce(...) // this is typesafe (as expected)

或者只加载我们要使用的函数

1
2
3
import * as debounce from 'lodash/debounce'
//work with the debounce function directly
debounce(...)   // this too is typesafe (as expected)

UPDATE - March 2017

我目前正在使用ES6 modules,最近我能够像这样使用lodash

1
2
3
4
5
6
// the-module.js (IT SHOULD WORK WITH TYPESCRIPT - .ts AS WELL)
// Load the full library...
import _ from 'lodash'
// work with whatever lodash functions we want
_.debounce(...) // this is typesafe (as expected)
...

OR import具体lodash functionality

1
2
3
4
import debounce from 'lodash/debounce'
//work with the debounce function directly
debounce(...)   // this too is typesafe (as expected)
...

注 - syntax中不需要* as的差异


参考文献:

enter image description here

祝好运。


自Typescript 2.0起,@ type npm模块用于导入输入。

1
2
3
4
5
# Implementation package (required to run)
$ npm install --save lodash

# Typescript Description
$ npm install --save @types/lodash

现在,由于这个问题已经得到解答,我将介绍如何有效地导入lodash

导入整个库的故障安全方法(在main.ts中)

1
import 'lodash';

这是新的一点:

使用您需要的功能实现更轻的lodash

1
2
3
4
5
import chain from"lodash/chain";
import value from"lodash/value";
import map from"lodash/map";
import mixin from"lodash/mixin";
import _ from"lodash/wrapperLodash";

来源:https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba#.kg6azugbd

PS:上面的文章是关于改进构建时间和减少应用程序大小的有趣读物


我使用以下命令在我的项目中成功导入了lodash:

1
2
npm install lodash --save
typings install lodash --save

然后我用以下方式导入它:

import * as _ from 'lodash';

在systemjs.config.js我定义了这个:

map: { 'lodash' : 'node_modules/lodash/lodash.js' }


我有完全相同的问题,但在Angular2应用程序中,本文只是解决它:https://medium.com/@s_eschweiler/using-external-libraries-with-angular-2-87e06db8e5d1#.p6gra5eli

文章摘要:

  • 安装库npm install lodash --save
  • 为Lodash tsd install underscore添加TypeScript定义
  • 包括脚本


    请注意,npm install --save将促进您的应用在生产代码中所需的任何依赖性。
    至于"typings",它只需要TypeScript,最终用JavaScript编译。因此,您可能不希望在生产代码中使用它们。我建议将它放在项目的devDependencies中,方法是使用

    1
    npm install --save-dev @types/lodash

    要么

    1
    npm install -D @types/lodash

    (例如参见Akash帖子)。顺便说一句,这是在ng2 tuto中完成的方式。

    或者,以下是package.json的外观:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    {
       "name":"my-project-name",
       "version":"my-project-version",
       "scripts": {whatever scripts you need: start, lite, ...},
        // here comes the interesting part
       "dependencies": {
          "lodash":"^4.17.2"
        }
       "devDependencies": {
           "@types/lodash":"^4.14.40"
        }
    }

    只是一个提示

    关于npm的好处是你可以先做一个npm install --save--save-dev,如果你不确定你正在寻找的最新版本的依赖项,它会自动为你设置它你的package.json供进一步使用。


    从lodash部分导入应使用以下符号在角度4.1.x中工作:

    1
    let assign = require('lodash/assign');

    或者使用'lodash-es'并导入模块:

    1
    import { assign } from 'lodash-es';


    我也创建了lodash-es的输入,所以现在你可以实际执行以下操作

    安装

    1
    2
    npm install lodash-es -S
    npm install @types/lodash-es -D

    用法

    1
    2
    import kebabCase from"lodash-es/kebabCase";
    const wings = kebabCase("chickenWings");

    如果你使用汇总,我建议使用它而不是lodash,因为它将正确树木。


    通过npm安装。

    1
    $ npm install lodash --save

    现在,文件中的import

    1
    $ import * as _ from 'lodash';

    ENV:

    Angular CLI: 1.6.6
    Node: 6.11.2
    OS: darwin x64
    Angular: 5.2.2
    typescript: 2.4.2
    webpack: 3.10.0


    如果以后不能工作

    1
    2
    $ npm install lodash --save
    $ npm install --save-dev @types/lodash

    你试试这个并导入lodash

    1
    typings install lodash --save


    通过typingstsd命令管理类型最终不赞成使用npm via npm install @types/lodash

    但是,我在导入语句中长时间与"无法找到模块lodash"进行斗争:

    1
    import * as _ from 'lodash';

    最终我意识到Typescript只会从node_modules / @ types start version 2加载类型,而我的VsCode语言服务仍然使用1.8,因此编辑器报告错误。

    如果您正在使用VSCode,则需要包含

    1
    "typescript.tsdk": "node_modules/typescript/lib"

    在VSCode settings.json文件中(用于工作区设置)并确保通过npm install [email protected] --save-dev安装了typescript version> = 2.0.0

    之后我的编辑不会抱怨import语句。


    我使用ng2与webpack,而不是系统JS。我需要的步骤是:

    1
    2
    npm install underscore --save
    typings install dt~underscore --global --save

    然后在文件中我希望将下划线导入:

    1
    import * as _ from 'underscore';

  • 安装lodash
  • <5233>

  • 在index.html中,为lodash添加地图:
  • System.config({
    packages: {
    app: {
    format: 'register',
    defaultExtension: 'js'
    }
    },
    map: {
    lodash: 'node_modules/lodash/index.js'
    }
    });

  • 在.ts代码中导入lodash模块
  • import _ from 'lodash';


    也许这太奇怪了,但首先没有一个帮助我,因为我已经正确安装了lodash(也通过以上建议重新安装)。

    长话短说,问题与使用lodash中的_.has方法有关。

    我通过简单地使用JS in运算符来修复它。


    我使用preboot / angular-webpack在Angular 4.0.0上,并且必须采用稍微不同的路线。

    @Taytay提供的解决方案主要适用于我:

    1
    2
    npm install --save lodash
    npm install --save @types/lodash

    并使用以下方法将函数导入给定的.component.ts文件:

    1
    import * as _ from"lodash";

    这是有效的,因为没有"默认"导出类。我的差异是我需要找到第三方库中加载的方式:vendor.ts,它位于:

    1
    src/vendor.ts

    我的vendor.ts文件现在看起来像这样:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import '@angular/platform-browser';
    import '@angular/platform-browser-dynamic';
    import '@angular/core';
    import '@angular/common';
    import '@angular/http';
    import '@angular/router';

    import 'rxjs';
    import 'lodash';

    // Other vendors for example jQuery, Lodash or Bootstrap
    // You can import js, ts, css, sass, ...


    安装所有通过终端:

    1
    2
    npm install lodash --save
    tsd install lodash --save

    在index.html中添加路径

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            },
            paths: {
                lodash: './node_modules/lodash/lodash.js'
            }
        });
        System.import('app/init').then(null, console.error.bind(console));

    在.ts文件的顶部导入lodash

    1
    import * as _ from 'lodash'


    您也可以通过良好的旧要求继续进口,即:

    1
    const _get: any = require('lodash.get');

    这是唯一对我们有用的东西。当然,确保在导入之后进行任何require()调用。


    尝试>> tsd install lodash --save