我有一个困难的时间试图得到lodash模块导入。我已经使用npm+gulp设置了我的项目,并不断撞击相同的墙。我试过普通的lodash,也试过lodash。

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

import * as _ from 'lodash';    

结果:

error TS2307: Cannot find module 'lodash'.

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

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中的modulerresolution:'node'应该将import语句指向node_modules文件夹,其中安装了lodash和lodash-es。我还尝试了许多不同的导入方法:绝对路径、相对路径,但似乎都不起作用。什么好主意吗?

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


尝试>> TSD安装lodash—保存

我也遇到了同样的问题,但在一个Angular2应用中,这篇文章只是解决了它:https://medium.com/@s_eschweiler/using-external-libraries-with-angular-2-87e06db8e5d1#.p6gra5eli

文章摘要:

npm安装lodash——save 为Lodash tsd安装下划线添加TypeScript定义 包括Script < Script src="node_modules/lodash/index.js"></ Script > .js System.config({ 道路:{ lodash:“。/ node_modules lodash / index.js ' import * as _ from ' lodash ';

希望对你的案子也有帮助

安装通通终端:

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'

2016年9月26日更新:

正如@Taytay的回答所说,我们现在可以使用几个月前使用的“typings”安装:

npm install --save @types/lodash

以下是支持这个答案的一些参考文献:

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

如果仍在使用类型安装,请参阅下面(其他人)关于“'——ambient''和'——global " ''的评论。

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

最初的回答:

这在我的mac上是有效的(在按照快速入门安装了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快速入门使用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行注释。

为了让我的测试与lodash一起工作,我还必须在karma.conf.js中的文件数组中添加一行:

'node_modules/lodash/lodash.js',

安装lodash

Sudo NPM安装类型—全局 NPM安装lodash—保存 类型安装lodash—ambient—保存

在index.html中,为lodash添加map:

System.config ({ 包:{ 应用:{ 格式:“注册”, defaultExtension:“js” } }, 地图:{ lodash:“node_modules / lodash index.js” } });

在.ts代码中导入lodash模块

Import _ from 'lodash';

步骤1:修改包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);

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

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

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

import * as _ from 'underscore';

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

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

然后我导入它的方式如下:

Import * as _ from 'lodash';

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

地图:“lodashs: node_modules/lodash/lodash。”

如果其他人遇到这个问题,并且由于“重复标识符”问题,上述解决方案都不起作用,运行这个:

npm install typings --global

对于旧版本的类型,事情会变得混乱,你会得到一堆“重复标识符”的问题。你也不需要再使用环境,就我所知。

因此,一旦类型是最新的,这应该可以工作(使用Angular 2快速入门)。

Run:

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

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

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

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

如果你仍然有问题,删除你的typings文件夹并运行npm install。

下面是如何做到这一点的Typescript 2.0: (tsd和类型不赞成以下):

$ 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中唯一可用的语法。他说,另一种建议的导入语法给出的错误是“没有默认导出”。

通过typeings和tsd命令管理类型最终被弃用,取而代之的是通过npm install @types/lodash来使用npm。

然而,我在import语句中“不能找到模块lodash”很长一段时间:

import * as _ from 'lodash';

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

如果你使用的是VSCode,你会想要包含

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

在你的VSCode设置。Json文件(用于工作空间设置),并确保通过NPM install typescript@2.0.2——save-dev安装了typescript版本>= 2.0.0

在那之后,我的编辑再也不会抱怨导入语句了。

从Typescript 2.0开始,@types 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:上面的文章是一篇关于改善构建时间和减少应用大小的有趣文章

重要的事情先说

NPM安装——保存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)

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

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

更新- 2017年3月

我目前正在使用ES6模块,最近我能够像这样使用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)
...

或导入特定的lodash功能:

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

注意-语法中不需要* as的区别

引用:

祝你好运。

请注意npm install——save将在生产代码中培养应用程序所需的任何依赖关系。 至于“类型”,它只被TypeScript要求,而TypeScript最终会转译成JavaScript。因此,您可能不希望在生产代码中使用它们。我建议把它放在项目的devDependencies中,使用

npm install --save-dev @types/lodash

or

npm install -D @types/lodash

(参见Akash的帖子)。顺便说一下,ng2 tuto就是这么做的。

或者,以下是你的包装方式。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,它会自动在你的包中为你设置。Json供进一步使用。

另一种优雅的解决方案是只获取所需的内容,而不是导入所有的lodash

import {forEach,merge} from "lodash";

然后在代码中使用它

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

我还为lodash创建了类型,所以现在您实际上可以执行以下操作

安装

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

使用

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

如果您使用rollup,我建议使用它而不是lodash,因为它将正确地进行树摇。

我在Angular 4.0.0上使用preboot/ Angular -webpack,不得不走一条稍微不同的路线。

@Taytay提供的解决方案对我来说很管用:

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

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

import * as _ from "lodash";

这是因为没有“默认”导出类。我的不同之处在于,我需要找到在第三方库中加载的方式:供应商。坐在那里的Ts:

src/vendor.ts

我的供应商。Ts文件现在看起来是这样的:

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, ...

从lodash部分导入应该在angular 4.1中工作。X使用以下符号:

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

或者使用'lodash-es'并在module中导入:

import { assign } from 'lodash-es';

如果不工作后

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

您尝试这样做并导入lodash

typings install lodash --save

通过npm安装。

$ npm install lodash --save

现在在文件中导入:

$ import * as _ from 'lodash';

ENV:

Angular CLI: 1.6.6 节点:6.11.2 操作系统:darwin x64 角:22 打印稿:2.4.2 webpack: 3.10.0

你也可以通过旧的require来导入,比如:

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

这是唯一对我们有效的方法。当然,要确保所有require()调用都在导入之后。

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

长话短说,这个问题与使用_有关。有方法从lodash。

我通过简单地在操作符中使用JS来修复它。

NPM install——save @types/lodash

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