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:

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay