Welcome to the first entry in a new series that’s probably going to stop with this first entry, or maybe not.
The series is called Charl’s Unwritten Rules of Software Development, or cursd.
I am also planning another series called Charl’s Unwritten Rules of Applied Machine Learning that is on its part probably going to remain in the planning stage, or maybe not.
Of course you are already making use of tslint’s ordered-imports rule, which means your within group ordering is consistent.
However, on that page you’ll see, amongst other things:
Groups of imports are delineated by blank lines. You can use this rule to group imports however you like, e.g. by first- vs. third-party or thematically or you can define groups based upon patterns in import path names.
The CURSD ordering of TypeScript import groups
Henceforth, the CURSD group ordering rule is:
We take our inspiration from the Python PEP8 recommendation:
Imports should be grouped in the following order:
Standard library imports. Related third party imports. Local application/library specific imports.
In Python that distinction is usually quite easy.
The example below should help clear this up.
In the example below, based on a component in an actual product, I have divided the imports up into three groups. At the start we have React and Redux, followed by the material-ui group, followed by our local modules and components.
If the list of imports became substantially longer, one could further divide up the local group into react components and non-component code.
We do this for at least two good reasons:
- This adds a light-weight hierarchical structure to the imports, which facilitates the understanding of the dependency network between all of the modules in your project.
- As is almost always the case, having conventions such as these frees up a few more mental cycles when writing code.
Bonus level: typescript-eslint rule for ordered import groups
Thanks to the suggestion by Frank van Wijk in the comments below, together with a bit of elbow grease on our part, we have now migrated from tslint to typescript-eslint.
As a component of that, I can now share the typescript-eslint rule that will enforce the import group ordering exactly as in the example above.
It looks like this: