我有一个困难的时间试图得到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文件来说明这个问题。


当前回答

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

其他回答

我也遇到了同样的问题,但在一个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 ';

希望对你的案子也有帮助

安装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';

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

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

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

import { assign } from 'lodash-es';

尝试>> TSD安装lodash—保存

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

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

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