DEV Community

Cover image for Force Lodash Import Scope
Agustinus Nathaniel
Agustinus Nathaniel

Posted on • Originally published at sznm.dev

Force Lodash Import Scope

Importing Lodash

There are multiple ways to import lodash utilities.

// whole import
import _ from 'lodash';
// _.debounce();

// curly bracket / named import
import { debounce } from 'lodash';

// one-by-one / modules / single method import
import debounce from 'lodash/debounce';
Enter fullscreen mode Exit fullscreen mode

One of the recommended way to import it is one-by-one or modules or single method import as it will produces smallest bundle size.

Enforce Lodash Import Method

How about if our project is:

  1. maintained by multiple people, or
  2. we have various parts in our code which utilize lodash

and we want to enforce specific way to import lodash methods?

We can use eslint and there's an eslint plugin for it: eslint-plugin-lodash. This plugin has a rule named import-scope. Here's how to configure it:

pnpm i -D eslint eslint-plugin-lodash
Enter fullscreen mode Exit fullscreen mode
// .eslintrc.js
/** @type {import('eslint').Linter.Config} */
module.exports = {
  plugins: ['lodash'],
  rules: {
    'lodash/import-scope': [
      'error',
      'method' /** 'method' | 'member' | 'full' | 'method-package' */,
    ],
  },
};
Enter fullscreen mode Exit fullscreen mode

With this configuration, eslint will warns us when we import lodash methods using other than the preferred import scope.

References:

Top comments (0)