Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 897
HJordan35 Avatar asked Sep 20 '19 15:09

HJordan35


1 Answers

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' 
like image 110
superdave Avatar answered Nov 18 '22 06:11

superdave