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"

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.js
const withTM = require("next-transpile-modules");

module.exports = withTM({
  transpileModules: ["lodash-es"]
});

Actually, you should not use lodash-es but to use lodash because lodash-es is esm module while lodash is our formal commonjs module.

However if you want to use lodash-es in node, you should use it with esm instead of @babel/register. I found @babel/register very buggy even if i have added babel-plugin-lodash or dynamic-import plugin or @babel/plugin-transform-modules-commonjs, @babel/polyfill, etc ...


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.