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
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.
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.
You can load types from here:
npm install --save-dev @types/lodash-es
And use it like:
import { camelCase } from "lodash-es"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With