将lodash导入angular2 + typescript应用程序

时间:2016-01-07 16:28:17

标签: javascript angular typescript lodash es6-module-loader

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

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

import * as _ from 'lodash';    

结果:

error TS2307: Cannot find module 'lodash'.

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

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

结果:

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

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

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

import 'lodash-es/lodash';

......但当然没有“_”......

我的tsconfig.json文件:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules"
  ]
}

我的gulpfile.js:

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文件来说明问题。

22 个答案:

答案 0 :(得分:387)

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

$ npm install --save lodash

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

然后,在.ts文件中:

或者:

import * as _ from "lodash";

或(由@Naitik建议):

import _ from "lodash";

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

2017年2月27日编辑:

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

答案 1 :(得分:61)

2016年9月26日更新:

正如@ Taytay的回答所说的那样,我们现在可以使用:

,而不是几个月前我们使用过的“打字”装置。
npm install --save @types/lodash

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

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

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

原始答案:

这适用于我的mac(根据Quick Start安装Angular 2之后):

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',如下所示:

System.config({
    packages: {
      app: {
        format: 'register',
        defaultExtension: 'js'
      }
    },
    map: {
      lodash: 'node_modules/lodash/lodash.js'
    }
  });

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

import _ from 'lodash';

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

2016年年中编辑:

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

import * as _ from 'lodash';

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

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

'node_modules/lodash/lodash.js',

答案 2 :(得分:24)

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

  "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。

(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 install

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

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

答案 3 :(得分:23)

首先是

npm install --save lodash

npm install -D @types/lodash

加载完整的lodash库

//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)

OR 仅加载我们将要使用的函数

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合作:

// 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)
...

import具体lodash functionality

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

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

<小时/>

参考文献:

enter image description here

祝你好运。

答案 4 :(得分:13)

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

# Implementation package (required to run)
$ npm install --save lodash

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

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

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

import 'lodash';

这是新位:

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

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:上面的文章是关于改进构建时间和减少应用程序大小的有趣读物

答案 5 :(得分:10)

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

npm install lodash --save
typings install lodash --save

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

import * as _ from 'lodash';

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

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

答案 6 :(得分:7)

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

文章摘要:

  1. 安装资料库npm install lodash --save
  2. 为Lodash添加TypeScript定义tsd install underscore
  3. 包含脚本<script src="node_modules/lodash/index.js"></script>
  4. 配置SystemJS System.config({ paths: { lodash: './node_modules/lodash/index.js'
  5. 导入模块import * as _ from ‘lodash’;
  6. 我希望它对你的情况也很有用

答案 7 :(得分:7)

另一个优雅的解决方案是只获得你需要的东西,而不是导入所有的lodash

import {forEach,merge} from "lodash";

然后在您的代码中使用它

forEach({'a':2,'b':3}, (v,k) => {
   console.log(k);
})

答案 8 :(得分:4)

如果其他人遇到此问题且上述解决方案均未因“重复标识符”问题而起作用,请运行以下命令:

npm install typings --global

对于旧版本的打字,事情搞得一团糟,你会得到一堆“重复标识符”问题。此外,根据我的意见,您不再需要使用--ambient

因此,一旦打字是最新的,这应该有效(使用Angular 2快速入门)。

执行命令

npm install lodash --save 
typings install lodash --save

首先,将其添加到systemjs.config.js:

'lodash':                     'node_modules/lodash/lodash.js'

现在您可以在任何文件中使用它:import * as _ from 'lodash';

如果您仍然遇到问题,请删除您的打字文件夹并运行npm install

答案 9 :(得分:4)

请注意npm install --save将促进您的应用在生产代码中所需的任何依赖性 对于&#34; typings&#34;,它只需要TypeScript,最终用JavaScript编译。因此,您可能不希望在生产代码中使用它们。我建议您使用

将其放入项目devDependencies
npm install --save-dev @types/lodash

npm install -D @types/lodash

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

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

{
    "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中自动为您设置以供进一步使用。

答案 10 :(得分:3)

我也为lodash-es创建了打字,所以现在你可以实际执行以下操作

安装

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

使用

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

如果你使用汇总,我建议使用它而不是lodash,因为它会被树木砍掉。

答案 11 :(得分:3)

lodash 的部分导入应使用以下表示法在 angular 4.1.x 中使用:

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

或者使用&#39; lodash-es&#39;并在模块中导入:

import { assign } from 'lodash-es';

答案 12 :(得分:2)

通过npm安装。

$ npm install lodash --save

现在,文件中的import

$ import * as _ from 'lodash';

<强> ENV:

  

Angular CLI:1.6.6
  节点:6.11.2
  操作系统:darwin x64
  Angular:5.2.2
  打字稿:2.4.2
  webpack:3.10.0

答案 13 :(得分:1)

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

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

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

import * as _ from 'underscore';

答案 14 :(得分:1)

最终不推荐通过typingstsd命令管理类型,而是通过npm install @types/lodash使用npm。

然而,我在导入声明中长时间难以找到“找不到模块lodash”:

import * as _ from 'lodash';

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

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

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

在VSCode settings.json文件中(用于工作区设置),并确保通过npm install typescript@2.0.2 --save-dev安装了打印版本&gt; = 2.0.0

之后我的编辑不会抱怨导入声明。

答案 15 :(得分:1)

  1. 安装lodash
  2. sudo npm install typings --global npm install lodash --save typings install lodash --ambient --save

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

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

答案 16 :(得分:1)

如果在

之后不起作用
$ npm install lodash --save 
$ npm install --save-dev @types/lodash

你试试这个并导入lodash

typings install lodash --save

答案 17 :(得分:0)

安装所有直通终端:

npm install lodash --save
tsd install lodash --save

在index.html中添加路径

<script>
    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));
</script>

在.ts文件的顶部导入lodash

import * as _ from 'lodash'

答案 18 :(得分:0)

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

很长一段时间,该问题与使用lodash中的_.has方法有关。

我只使用JS in运算符修复了它。

答案 19 :(得分:0)

npm install --save @types/lodash

https://www.npmjs.com/package/@types/lodash

答案 20 :(得分:-1)

尝试&gt;&gt; tsd install lodash --save

答案 21 :(得分:-1)

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

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

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