Skip to content

Instantly share code, notes, and snippets.

@alexilyaev
Last active August 4, 2023 06:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexilyaev/eb17fb0b1e893c7f425f2cdf76b2ea14 to your computer and use it in GitHub Desktop.
Save alexilyaev/eb17fb0b1e893c7f425f2cdf76b2ea14 to your computer and use it in GitHub Desktop.
Import Aliases Setup

Import Aliases

In an effort to keep import statements clean and easy to work with, we can use import aliases.

For example (anywhere in the app or src tree):

import { network } from 'lib/network';
import { colors } from 'styles/theme';
import useThrottledEvent from 'hooks/useThrottledEvent';
import Logo from 'public/media/logo.png';
import Typography from 'components/shared/Typography/Typography';

To make this possible, there are several places we need to configure, depending on what we use…

TypeScript/IDE

  • tsconfig.json or jsconfig.json
  • paths - IDE support for Jump To Definition and IntelliSense
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "public/*": ["public/*"],
    }
  },
}

Note for non-bundler Node.js projects

When using tsc to compile TypeScript files:

Note that this feature does not change how import paths are emitted by tsc, so paths should only be used to inform TypeScript that another tool has this mapping and will use it at runtime or when bundling.

Supporting import aliases for such projects is more complicated, as Node won’t know how to resolve the aliases during runtime.

Solution

Extra work for aliasing external packages or local monorepo packages

ESLint

'import/resolver': {
  node: {
    moduleDirectory: ['node_modules', __dirname, 'src'],
  },
},
'import/resolver': {
  typescript: {
    alwaysTryTypes: true,
    project: `${__dirname}/tsconfig.json`,
  },
},
'import/order': [
  'warn',
  {
    groups: [
      'builtin',
      'external',
      'internal',
      'parent',
      'sibling',
      'index',
      'unknown',
    ],
    // Import aliases
    pathGroups: [
      'lib',
      'hooks',
      'public',
      'components',
    ].map(identifier => ({
      pattern: `${identifier}/**`,
      group: 'internal',
      position: 'after',
    })),
    'newlines-between': 'always',
  },
],

Webpack/Next.js

config.resolve.modules = ['node_modules', path.resolve(cwd, 'src')];
config.resolve.alias = {
  ...config.resolve.alias,
  public: path.resolve(cwd, 'public'),
};

Jest

moduleDirectories: ['node_modules', 'src'],
moduleNameMapper: {
  public: '<rootDir>/public',
}

Storybook

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment