2

Auto-fixable import sorting rules for ESLint

 2 years ago
source link: https://dev.to/bmstefanski/auto-fixable-import-sorting-rules-for-eslint-laj
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cover image for Auto-fixable import sorting rules for ESLint
Bartłomiej Stefański

Posted on Nov 26

• Originally published at bstefanski.com

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
Enter fullscreen modeExit fullscreen mode
// .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 modeExit fullscreen mode

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK