How to use lodash-es in typescript correctly?
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.
I just ran into this and this works for me:
import { upperCase } from 'lodash-es'; // works :)import upperCase from 'lodash-es/upperCase'; // broken :(
[edit]
So I just restarted my application and now it's no longer working and I haven't made any configuration changes. Amazing.
[edit 2]
I found out that the problem probably lies in the lodash-es
module not being transpiled out of the box, and you need to tell Webpack or Babel to do so. Here is a blog post providing some good insight: https://medium.com/@martin_hotell/tree-shake-lodash-with-webpack-jest-and-typescript-2734fa13b5cd. The article also covers how to fix the issue for Jest if you're using that.
If you're using NextJS, you can use https://github.com/martpie/next-transpile-modules
// next.config.jsconst withTM = require("next-transpile-modules");module.exports = withTM({ transpileModules: ["lodash-es"]});