首页 > 解决方案 > 如何在打字稿中正确使用 lodash-es?

问题描述

我需要lodash-es在我的打字稿项目中使用,但我无法正确配置它,它总是报告错误,例如SyntaxError: Unexpected identifier

你好.ts

import upperCase from 'lodash-es/upperCase'

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

包.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

一个相关的问题是将 lodash-es 与 babel 一起使用:如何正确配置 babel 以使用 lodash-es?. 由于我不确定他们是否有完全相同的原因,所以我在这里要求打字稿

标签: typescriptts-nodelodash

解决方案


您可以从这里加载类型:

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

并像这样使用它:

import { camelCase } from "lodash-es"

推荐阅读