Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lodash-es in typescript correctly?

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

like image 491
Freewind Avatar asked Oct 17 '18 10:10

Freewind


People also ask

Can we use lodash in TypeScript?

Consuming. From there you'll be able to use lodash in your TypeScript code with no fuss. This works for both modules and global code.

What is lodash-es used for?

Lodash helps programmers write more concise and easier to maintain JavaScript code. Lodash contains tools to simplify programming with strings, numbers, arrays, functions and objects. By convention, Lodash module is mapped to the underscore character.


2 Answers

You can load types from here:

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

And use it like:

import { camelCase } from "lodash-es"
like image 116
atilkan Avatar answered Sep 17 '22 15:09

atilkan


ts-node compiles .ts files as they are loaded. It doesn't touch .js files; either they must already be in a form understood by Node.js (e.g., no ES6 import statements) or you must use a separate mechanism to transform them, such as the @babel/register require hook (essentially the same thing that is used by babel-node). You would still need to configure @babel/register not to ignore node_modules, as described in the other answer. The advice from the other answer to just use lodash instead of lodash-es is good.

like image 25
Matt McCutchen Avatar answered Sep 18 '22 15:09

Matt McCutchen