Organizing Imports in React and React Native
We have already used ESLint and Prettier to enforce code quality and formatting rules. Now let's go one step further and try to make sure that the import statements we have are a bit more organized.
This will also help us visualize our codebase and quickly grasp where we are importing from.
This is what we are aiming for :
1. Group by origin
We will group system libraries (like react), external libraries, and internal project imports separately. (I also prefer to insert an empty line between each group to visually separate them)
2. Sort within each group
Within each group, we will sort the import declarations by their source
3. Sort within each import declaration
And lastly, we will ensure that individual imports within each declaration are also sorted.
VSCode (with extensions) supports some level of import sorting. But we are after a solution that we can also run from the command line, and ideally becomes part of our pre-commit hooks. (Same as for the lining and formatting)
ESLint to the rescue again!
We will be using eslint-plugin-import
to accomplish the first two levels. And we will use the internal sort-order
rule for the last one.
Let's install the ESLint plugin:
yarn add -D eslint-plugin-import
Then we will make two changes to our .eslintrc.js
. We will add the new plugin under plugins
, and add new rules
to enforce this grouping and sorting.
We are declaring these as errors, so they can be auto-fixed by ESLint during the file save, as well as any command-line invocation (including pre-commit hooks)
This is how our .eslintrc.js
looks like now:
module.exports = {
//... existing
plugins: [...(existing plugins), 'import'],
rules: {
// this is for sorting WITHIN an import
'sort-imports': ['error', {ignoreCase: true, ignoreDeclarationSort: true}],
// this is for sorting imports
'import/order': [
'error',
{
groups: [
['external', 'builtin'],
'internal',
['sibling', 'parent'],
'index',
],
pathGroups: [
{
pattern: '@(react|react-native)',
group: 'external',
position: 'before',
},
{
pattern: '@src/**',
group: 'internal',
},
],
pathGroupsExcludedImportTypes: ['internal', 'react'],
'newlines-between': 'always',
alphabetize: {
order: 'asc',
caseInsensitive: true,
},
},
],
},
};
And we are done. Enjoy your newly organized imports!