2

I have been absent from nodejs development for a few years, and to my surprise when I did

$ npm install lodash

the size of my node_modules grew by 4.8MiB

how come a library that judging by its source line count should be around 260KiB takes so much space?

I am deploying my code as an AWS Lambda, and the ability to edit and debug in the console is lost due the increased size of my distribution file (partly because of this).

What's the 2019 way to deal with this?

fortran
  • 74,053
  • 25
  • 135
  • 175

2 Answers2

1

You node_modules size is irrelevant.

If you build you application the size is much much smaller:

  • minified 69.2kb
  • minified + gzipped 24.3kB

see here

Norbert Bartko
  • 2,468
  • 1
  • 17
  • 36
  • well, my distribution must include the `node_modules` I cannot see how that is irrelevant – fortran Sep 19 '19 at 12:50
  • 1
    Then you maybe should rethink your distribution. Thats why we have npm, to install our packages independent whereever we want to. – Norbert Bartko Sep 19 '19 at 13:17
0

If you're using Webpack, ESBuild, or a similar bundler with tree-shaking capabilities, you can import lodash functions discretely.

import foo from 'lodash/foo';

Support for this syntax was added in Lodash v4.

Note the syntax should be 'lodash/foo'. Contrarily, import { foo } from 'lodash' will not be tree-shaken.

Like Norbert said, your node_modules size is irrelevant. You'll want to look at the size of your bundle after building your application. In the case of Webpack, you can use Webpack Bundle Analyzer to gain additional insights into your bundle's distribution. For Vite and other toolchains that use Rollup, consider rollup-plugin-visualizer.

Here's a few more tips:

  • As of lodash v4, tree-shaking works without additional configuration in Webpack >= v4 and ESBuild. If you use lodash-es and you have other dependencies that require lodash, both will end up in your bundle.

  • If you're using Babel, and you don't want to refactor your entire codebase to use the aforementioned lodash/foo syntax, consider using babel-plugin-lodash. This plugin rewrites lodash import statements to use the tree-shaking syntax for you.

  • If you're using Babel's preset-env plugin, set the modules option to false. Babel rewrites modules to use CommonJS by default, which won’t tree-shake.

  • If you're only using a single Lodash function, you can install it as a standalone module in lieu of installing the entire lodash package. e.g. npm install --save lodash.functionName

  • lodash-es introduces a few exceptions to this strategy. Refer to this answer for more insight into this.

goldmund
  • 21
  • 1
  • 1
  • 2