Lodash is bigger than you think

#1

This PR is a fun little example of how a tiny change in usage patterns can cause a huge impact in how much code you’re pulling into your app:

8 Likes

#2

@ef4 Thanks for posting this! I will definitely apply this pattern to my use of lodash.

How does this differ from using named imports, e.g. import { isFunction } from 'lodash'? Curious if that would reap the same benefit. Found a codemod that partly does that transform.

For context, if you are using ember-auto-import for lodash or other dependencies, when analyzing the output with ember-cli-bundle-analyzer, you may not see those dependencies included in the analysis. This is a known issue:

0 Likes

#3

If you’re using plain lodash, the main entrypoint file is not authored as an ES module, so you definitely will not be able to strip out the unused parts.

But if you switch to lodash-es, you get an entrypoint that is an ES module. By itself, that’s still not enough to drop unused exports, but Webpack 4 (as used inside ember-auto-import) looks for a webpack-specific sideEffects: false setting in package.json that allows libraries to declare that it’s safe to strip unused imports. lodash-es has that setting, so it should work the way you’d hope.

Oh yes, I have a better workaround I can suggest for this now. It doesn’t give you one complete picture, but it gives you a separate report for the things that auto-imported:

// 1. yarn add --dev webpack-bundle-analyzer
// 2. Configure auto-import like this:
autoImport: {
  webpack: {
    plugins: [
      new (require("webpack-bundle-analyzer")).BundleAnalyzerPlugin(),
    ],
  },
},
// 3. ember server
2 Likes

#4

I started a codemod to migrate usage for anyone that has multiple references and doesn’t want to manually migrate them:

Handful of things still left but this rewrites most simple uses. If I get some time in the next month I hope to polish this.

3 Likes