如何在TypeScript中正确使用lodash-es?

25

我需要在我的 TypeScript 项目中使用 lodash-es,但是我无法正确配置它,它总是报告类似于 SyntaxError: Unexpected identifier 的错误。

hello.ts

import upperCase from 'lodash-es/upperCase'

console.log('Hello ' + upperCase('typescript') + '!');

package.json

{
  "scripts": {
    "demo": "ts-node hello.ts"
  },
  "dependencies": {
    "lodash-es": "4.17.11"
  },
  "devDependencies": {
    "@types/lodash-es": "4.17.1",
    "ts-node": "7.0.0",
    "typescript": "3.0.1"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs"
  }
}
当运行ts-node hello.ts时,会报告以下错误:
/typescript-use-lodash-es-demo/node_modules/lodash-es/upperCase.js:1
    (function (exports, require, module, __filename, __dirname) { import createCompounder from './_createCompounder.js';
                                                                         ^^^^^^^^^^^^^^^^

    SyntaxError: Unexpected identifier
        at new Script (vm.js:79:7)
        at createScript (vm.js:251:10)

我还为这个问题设置了一个小演示,如果您需要的话,可以克隆并尝试:https://github.com/freewind-demos/typescript-use-lodash-es-demo

另外一个相关问题是如何在babel中使用lodash-es: How to configure babel correctly to use lodash-es?。由于我不确定它们完全相同的原因,所以我在这里询问了typescript。

4个回答

17

您可以从此处加载类型:

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

然后像这样使用:

import { camelCase } from "lodash-es"

3
ts-node会在加载时编译.ts文件,不会改变.js文件;.js文件必须已经符合Node.js的要求(例如没有ES6的import语句),或者您必须使用其他机制转换它们,例如@babel/register require hook(实际上和babel-node使用的是同一种方法)。您仍然需要配置@babel/register以便不忽略node_modules,如其他回答所述。只使用lodash而不是lodash-es的建议是好的。

3

我刚刚遇到了这个问题,以下方法对我有效:

import { upperCase } from 'lodash-es'; // works :)
import upperCase from 'lodash-es/upperCase'; // broken :(

[编辑]

我刚刚重启了我的应用程序,现在它不再工作了,而我没有进行任何配置更改。太神奇了。

[编辑 2]

我发现问题可能在于lodash-es模块没有被直接转译,需要告诉Webpack或Babel进行转译。这里有一篇博客文章提供了一些很好的见解:https://medium.com/@martin_hotell/tree-shake-lodash-with-webpack-jest-and-typescript-2734fa13b5cd。该文章还讲述了如何修复Jest的问题(如果你正在使用Jest)。

如果你正在使用NextJS,则可以使用https://github.com/martpie/next-transpile-modules

// next.config.js
const withTM = require("next-transpile-modules");

module.exports = withTM({
  transpileModules: ["lodash-es"]
});

2
注意,在当前版本的 next-transpile-modules 中,只需使用 withTM(['lodash-es']) - cbr

2
实际上,你不应该使用lodash-es,而是要使用lodash,因为lodash-esesm模块,而lodash是我们正式的commonjs模块。
但是,如果你想在Node中使用lodash-es,你应该使用esm而不是@babel/register。我发现@babel/register即使我添加了babel-plugin-lodashdynamic-import插件或@babel/plugin-transform-modules-commonjs@babel/polyfill等也会出现很多问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接