DEV Community

Bartłomiej Stefański
Bartłomiej Stefański

Posted on • Originally published at bstefanski.com on

✨ Auto-fixable import sorting rules for ESLint

The pretty much standard way of sorting imports in JavaScript:

  • 3rd party imports first
  • then local default exports
  • and then local exports

And here's the snippet that sorts them in this exact order and satisfies my needs completely!


$ npm i --save-dev eslint-plugin-import

# or 

$ yarn add -D eslint-plugin-import



// .eslintrc.js 

const fs = require('fs')

const ignoredSortingDirectories = ['.git', '.next', '.vscode', 'node\_modules']

module.exports = {

/// ... some other configurations 

 rules: {

// ... your rules 

'sort-imports': ['error', { ignoreCase: true, ignoreDeclarationSort: true }],

'import/order': [

1,

{

 groups: ['external', 'builtin', 'internal', 'sibling', 'parent', 'index'],

 pathGroups: [

...getDirectoriesToSort().map((singleDir) => ({ pattern: `${singleDir}/\*\*`, group: 'internal' })),

{ pattern: 'env', group: 'internal' },

{ pattern: 'theme', group: 'internal' },

{ pattern: 'public/\*\*', group: 'internal', position: 'after' },

],

 pathGroupsExcludedImportTypes: ['internal'],

 alphabetize: {

 order: 'asc',

 caseInsensitive: true,

},

},

],

// ... your rules 

},

}

function getDirectoriesToSort() {

return getDirectories(process.cwd()).filter((f) => !ignoredSortingDirectories.includes(f))

}

function getDirectories(path) {

return fs.readdirSync(path).filter(function (file) {

return fs.statSync(path + '/' + file).isDirectory()

})

}

Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

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

Okay