Last active
August 2, 2021 11:09
-
-
Save adriencaccia/761ecb78b9f5e8297c0bda5bc3fd7f78 to your computer and use it in GitHub Desktop.
Automatic eslint import/order groups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const generateImportOrderRule = require('generateImportOrderRule'); | |
| module.exports = { | |
| ... | |
| rules: { | |
| ... | |
| 'import/order': generateImportOrderRule(__dirname), | |
| ... | |
| } | |
| ... | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const { readdirSync } = require('fs'); | |
| const path = require('path'); | |
| const filterDirent = (dirent) => | |
| dirent.isDirectory() || | |
| (dirent.name.includes('.ts') && !dirent.name.includes('.test.ts')); | |
| const formatPathGroupsFromDirent = (dirent) => ({ | |
| pattern: dirent.isDirectory() | |
| ? `${dirent.name}{,/**}` | |
| : dirent.name.replace('.ts', ''), | |
| group: 'internal', | |
| }); | |
| const generateImportOrderRule = (dirname, tsConfigPath = 'tsconfig.json') => { | |
| const tsConfig = require(path.resolve(dirname, tsConfigPath)); | |
| const tsConfigPaths = Object.keys(tsConfig.compilerOptions.paths || {}).map( | |
| (currentPath) => ({ | |
| pattern: `${currentPath}*`, | |
| group: 'internal', | |
| }) | |
| ); | |
| const baseUrlPaths = readdirSync( | |
| path.resolve(dirname, tsConfig.compilerOptions.baseUrl), | |
| { | |
| withFileTypes: true, | |
| } | |
| ) | |
| .filter(filterDirent) | |
| .map(formatPathGroupsFromDirent); | |
| const pathGroups = [...tsConfigPaths, ...baseUrlPaths]; | |
| return [ | |
| 'error', | |
| { | |
| pathGroups, | |
| groups: [ | |
| ['external', 'builtin'], | |
| 'internal', | |
| ['parent', 'sibling', 'index'], | |
| ], | |
| alphabetize: { | |
| order: 'asc', | |
| caseInsensitive: false, | |
| }, | |
| 'newlines-between': 'always', | |
| pathGroupsExcludedImportTypes: ['builtin'], | |
| }, | |
| ]; | |
| }; | |
| module.exports = generateImportOrderRule; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment