Skip to content

Instantly share code, notes, and snippets.

@adriencaccia
Last active August 2, 2021 11:09
Show Gist options
  • Select an option

  • Save adriencaccia/761ecb78b9f5e8297c0bda5bc3fd7f78 to your computer and use it in GitHub Desktop.

Select an option

Save adriencaccia/761ecb78b9f5e8297c0bda5bc3fd7f78 to your computer and use it in GitHub Desktop.
Automatic eslint import/order groups
const generateImportOrderRule = require('generateImportOrderRule');
module.exports = {
...
rules: {
...
'import/order': generateImportOrderRule(__dirname),
...
}
...
};
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