How to use lodash-es in typescript correctly?

Freewind picture Freewind · Oct 17, 2018 · Viewed 9.9k times · Source

I need to use lodash-es in my typescript project, but I can't configure it correctly, it always reports errors like 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"
  }
}

When run ts-node hello.ts, it reports error like:

/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)

I've also setup a small demo for this issue, you can clone and try it if you need: https://github.com/freewind-demos/typescript-use-lodash-es-demo

A related question is to use lodash-es with babel: How to configure babel correctly to use lodash-es?. Since I'm not sure they have exactly the same reason, so I asked for typescript here

Answer

atilkan picture atilkan · Jan 20, 2020

You can load types from here:

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

And use it like:

import { camelCase } from "lodash-es"