Reduce Lodash in bundle using 'lodash-es' and create-react-app
Asked Answered
F

2

6

I am a novice when it comes to webpack, and I have always relied on the out-of-the-box capabilities of tools like create-react-app when it comes to build processing. However, I am just now starting to "try" and get more into things - so please forgive my novice understanding.

We are using Lodash throughout our application, and we are trying to ensure we only import what we need. From what I have seen, there are 2 ways to import:

  1. import assign from 'lodash/assign';
  2. import {assign} from 'lodash-es';

I personally prefer the second option, because you can combine all of your imports into a single line if you are using multiple Lodash functions.

So I installed the lodash-es library, removed lodash from my package.json, updated all of the imports, and then ran a clean build. However, when I use source-map-explorer to view the bundle, I am seeing references to lodash-es as well as lodash even though I do not have lodash listed in my package.json. I assume it is because it is shipped somewhere in create-react-app. See my source map below...

Example Sourcemap using import {assign} from 'lodash-es' convention enter image description here

I assumed this was a bad thing, and thought that I was probably "double importing" lodash functions that are already being used/imported in create-react-app. So I tried using option 1. to do my imports. However, to my surprise, it actually appears that the the total size of the application is larger and the size of lodash imports is actually ~3k more than when using option 2!

Example Sourcemap using import assign from 'lodash/assign' convention enter image description here

So my question is - Am I interpreting the sourcemap correctly in that lodash-es is actually a more efficient way to import, and "double-importing" isn't actually a risk. Or is option 1 convention the best way to approach imports with lodash?

Fantast answered 20/9, 2019 at 15:36 Comment(0)
F
2

Two things:

You can remove double importing by alias'ing the lodash to lodash-es in the webpack config:

module.exports = {
  resolve: {
    alias: {
      'lodash-es': 'lodash',
    },
  },
};

Secondly, to be more explicit for importing only what you need from lodash-es, you may want to import lodash functions in the following way:

import assign from 'lodash-es/assign' 
Feuillant answered 9/12, 2020 at 6:48 Comment(0)
E
0

Just improving on @superdave's answer that you need to resolve one into another, in my case replacing lodash with lodash-es worked and lodash is no longer the part of output:

module.exports = {
  resolve: {
    alias: {
      'lodash': 'lodash-es',
    },
  },
};
Echolocation answered 2/1, 2023 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.