Javascript 将 lodash 导入 angular2 + typescript 应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34660265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:42:25  来源:igfitidea点击:

Importing lodash into angular2 + typescript application

javascriptangulartypescriptlodashes6-module-loader

提问by Davy

I am having a hard time trying to get the lodash modules imported. I've setup my project using npm+gulp, and keep hitting the same wall. I've tried the regular lodash, but also lodash-es.

我很难尝试导入 lodash 模块。我已经使用 npm+gulp 设置了我的项目,并且一直在碰壁。我试过普通的 lodash,也试过 lodash-es。

The lodash npm package: (has an index.js file in the package root folder)

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

import * as _ from 'lodash';    

Results in:

结果是:

error TS2307: Cannot find module 'lodash'.

The lodash-es npm package: (has a defaut export in lodash.js i the package root folder)

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

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

Results in:

结果是:

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

Both the gulp task and webstorm report the same issue.

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

Funny fact, this returns no error:

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

import 'lodash-es/lodash';

... but of course there is no "_" ...

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

My tsconfig.json file:

我的 tsconfig.json 文件:

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

My gulpfile.js:

我的 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']);

If i understand correctly, moduleResolution:'node' in my tsconfig should point the import statements to the node_modules folder, where lodash and lodash-es are installed. I've also tried lots of different ways to import: absolute paths, relative paths, but nothing seems to work. Any ideas?

如果我理解正确,我的 tsconfig 中的 moduleResolution:'node' 应该将导入语句指向 node_modules 文件夹,其中安装了 lodash 和 lodash-es。我也尝试了很多不同的导入方式:绝对路径、相对路径,但似乎没有任何效果。有任何想法吗?

If necessary i can provide a small zip file to illustrate the problem.

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

回答by Taytay

Here is how to do this as of Typescript 2.0: (tsd and typings are being deprecated in favor of the following):

以下是从 Typescript 2.0 开始如何执行此操作:(不推荐使用 tsd 和typings 以支持以下内容):

$ npm install --save lodash

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

Then, in your .ts file:

然后,在您的 .ts 文件中:

Either:

任何一个:

import * as _ from "lodash";

Or (as suggested by @Naitik):

或者(如@Naitik 所建议的):

import _ from "lodash";

I'm not positive what the difference is. We use and prefer the first syntax. However, some report that the first syntax doesn't work for them, and someone else has commented that the latter syntax is incompatible with lazy loaded webpack modules. YMMV.

我不肯定有什么区别。我们使用并更喜欢第一种语法。然而,有些人报告说第一种语法对他们不起作用,还有人评论说后一种语法与延迟加载的 webpack 模块不兼容。天啊。

Edit on Feb 27th, 2017:

2017 年 2 月 27 日编辑:

According to @Koert below, import * as _ from "lodash";is the only working syntax as of Typescript 2.2.1, lodash 4.17.4, and @types/lodash 4.14.53. He says that the other suggested import syntax gives the error "has no default export".

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

回答by Marcus

Update September 26, 2016:

2016 年 9 月 26 日更新:

As @Taytay's answer says, instead of the 'typings' installations that we used a few months ago, we can now use:

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

npm install --save @types/lodash

Here are some additional references supporting that answer:

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

If still using the typings installation, see the comments below (by others) regarding '''--ambient''' and '''--global'''.

如果仍在使用打字安装,请参阅下面(由其他人)关于 '''--ambient''' 和 '''--global''' 的评论。

Also, in the new Quick Start, config is no longer in index.html; it's now in systemjs.config.ts (if using SystemJS).

此外,在新的 Quick Start 中,config 不再在 index.html 中;它现在在 systemjs.config.ts 中(如果使用 SystemJS)。

Original Answer:

原答案:

This worked on my mac (after installing Angular 2 as per Quick Start):

这在我的 mac 上工作(在按照Quick Start安装 Angular 2 之后):

sudo npm install typings --global
npm install lodash --save 
typings install lodash --ambient --save

You will find various files affected, e.g.

您会发现各种受影响的文件,例如

  • /typings/main.d.ts
  • /typings.json
  • /package.json
  • /打字/main.d.ts
  • /typings.json
  • /package.json

Angular 2 Quickstart uses System.js, so I added 'map' to the config in index.html as follows:

Angular 2 Quickstart 使用 System.js,所以我在 index.html 的配置中添加了“map”,如下所示:

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

Then in my .ts code I was able to do:

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

import _ from 'lodash';

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

Edits from mid-2016:

2016 年年中的编辑:

As @tibbus mentions, in some contexts, you need:

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

import * as _ from 'lodash';

If starting from angular2-seed, and if you don't want to import every time, you can skip the map and import steps and just uncomment the lodash line in tools/config/project.config.ts.

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

To get my tests working with lodash, I also had to add a line to the files array in karma.conf.js:

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

'node_modules/lodash/lodash.js',

回答by Akash

First things first

第一件事

npm install --save lodash

npm install --save lodash

npm install -D @types/lodash

npm install -D @types/lodash

Load the full lodash library

加载完整的 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)

ORload only functions we are going to work with

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

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



UPDATE - March 2017

UPDATE - March 2017

I'm currently working with ES6 modules, and recently i was able to work with lodashlike so:

我目前正在与 一起工作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)
...

OR importspecific lodash functionality:

import具体lodash functionality

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

NOTE- the difference being * asis not required in the syntax

注意- 差异* as不需要在syntax



References:

参考:

enter image description here

在此处输入图片说明

Good Luck.

祝你好运。

回答by Vi137

Step 1: Modify package.json file to include lodash in the dependencies.

第 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"  }

Step 2:I am using SystemJs module loader in my angular2 application. So I would be modifying the systemjs.config.js file to map lodash.

第 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);

Step 3: Now do npm install

第 3 步:现在执行 npm install

Step 4: To use lodash in your file.

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

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

回答by Dhruvan Ganesh

Since Typescript 2.0, @types npm modules are used to import typings.

从 Typescript 2.0 开始,@types npm 模块用于导入类型。

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

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

Now since this question has been answered I'll go into how to efficiently import lodash

现在既然这个问题已经回答了,我将讨论如何有效地导入 lodash

The failsafe way to import the entire library (in main.ts)

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

import 'lodash';

This is the new bit here:

这是这里的新内容:

Implementing a lighter lodash with the functions you require

使用您需要的功能实现更轻量级的 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";

source: https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba#.kg6azugbd

来源:https: //medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba#.kg6azugbd

PS: The above article is an interesting read on improving build time and reducing app size

PS:上面的文章是一篇关于提高构建时间和减少应用程序大小的有趣读物

回答by smartmouse

I successfully imported lodash in my project with the following commands:

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

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

Then i imported it in the following way:

然后我通过以下方式导入它:

import * as _ from 'lodash';

import * as _ from 'lodash';

and in systemjs.config.js i defined this:

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

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

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

回答by maufarinelli

I had exactly the same problem, but in an Angular2 app, and this article just solve it: https://medium.com/@s_eschweiler/using-external-libraries-with-angular-2-87e06db8e5d1#.p6gra5eli

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

Summary of the article:

文章摘要:

  1. Installing the Library npm install lodash --save
  2. Add TypeScript Definitions for Lodash tsd install underscore
  3. Including Script <script src="node_modules/lodash/index.js"></script>
  4. Configuring SystemJS System.config({ paths: { lodash: './node_modules/lodash/index.js'
  5. Importing Module import * as _ from ‘lodash';
  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';

I hope it can be useful for your case too

我希望它对你的情况也有用

回答by Pian0_M4n

Another elegant solution is to get only what you need, not import all the lodash

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

import {forEach,merge} from "lodash";

and then use it in your code

然后在你的代码中使用它

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

回答by avi.elkharrat

Please note that npm install --savewill foster whatever dependency your app requires in production code.
As for "typings", it is only required by TypeScript, which is eventually transpiled in JavaScript. Therefore, you probably do not want to have them in production code. I suggest to put it in your project's devDependenciesinstead, by using

请注意,这npm install --save将促进您的应用程序在生产代码中所需的任何依赖项。
至于“打字”,只有 TypeScript 需要它,最终在 JavaScript 中进行转换。因此,您可能不希望在生产代码中使用它们。我建议把它放在你的项目中devDependencies,使用

npm install --save-dev @types/lodash

or

或者

npm install -D @types/lodash

(see Akash post for example). By the way, it's the way it is done in ng2 tuto.

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

Alternatively, here is how your package.json could look like:

或者,您的 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"
    }
}

just a tip

只是一个提示

The nice thing about npmis that you can start by simply do an npm install --saveor --save-devif you are not sure about the latest available version of the dependency you are looking for, and it will automatically set it for you in your package.jsonfor further use.

好的一点npm是,您可以简单地开始,npm install --save或者--save-dev如果您不确定您正在寻找的依赖项的最新可用版本,它会自动为您设置它以package.json供进一步使用。

回答by Bart

If anyone else runs into this issue and none of the above solutions work due to "Duplicate identifier" issues, run this:

如果其他人遇到此问题并且由于“重复标识符”问题而上述解决方案均无效,请运行以下命令:

npm install typings --global

With older versions of typings things mess up and you'll get a bunch of "Duplicate identifier" issues. Also you don't need to use --ambientanymore as far as I could tell.

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

So once typings is up to date, this should work (using the Angular 2 quickstart).

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

Run:

跑:

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

First, add this to systemjs.config.js:

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

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

Now you can use this in any file: import * as _ from 'lodash';

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

Delete your typings folder and run npm installif you're still having issues.

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