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


当前回答

通过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

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

其他回答

步骤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);

从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 install lodash --save 
$ npm install --save-dev @types/lodash

您尝试这样做并导入lodash

typings install lodash --save

安装通通终端:

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'

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

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。