Skip to content

(Opinionated) Structuring and ordering of imports

Ole Anders Stokker edited this page Apr 25, 2019 · 2 revisions

There are a lot of way you can order your imports, and different IDEs or editors do it in different ways by default.

I have found that for me, the best way to do it is to divide it into 3 blocks.

  • external import
  • root-relative imports
  • and local imports

This is to make it clearer where modules come from, and to make it easier to get a better understanding of the larger application.

It also helps a lot in files with a lot of imports, to not make it just a large pile of imports.

Lastly is orders them in a clean manner when they are ordered alphabetically, as our lord tslint demands.

External imports

These are imports of external packages, like React. They should be put on top.

import React, { useState } from 'react';

Root-relative imports

This project has been set up with a base folder, which is the src folder. This means any import can be done relative to that.

Any file not residing in the same module as the current file should be imported with a root relative route.

It may be a good thing to import as root relative if the path looks like this as well: ../../../models/Something; But I won't strictly condone that.

import { Link } from 'core/component/Router';
import { IEvent } from 'event/models/Event';

local imports

The last block of imports is local imports.

These are mostly imports inside the same folder or sub-folders.

import { Content } from './Content';
import { Header } from './Header';

Put together

Each import type has its' own block.

import React, { useState } from 'react';

import { Link } from 'core/component/Router';
import { IEvent } from 'event/models/Event';

import { Content } from './Content';
import { Header } from './Header';