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


当前回答

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

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

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

import * as _ from 'underscore';

其他回答

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

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。

NPM install——save @types/lodash

https://www.npmjs.com/package/@types/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'

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

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

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

Import * as _ from 'lodash';

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

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

尝试>> TSD安装lodash—保存