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…
tsconfig.json
orjsconfig.json
- paths - IDE support for Jump To Definition and IntelliSense
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"public/*": ["public/*"],
}
},
}
When using tsc
to compile TypeScript files:
Note that this feature does not change how import paths are emitted by
tsc
, sopaths
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.
- https://github.com/ilearnio/module-alias
- https://levelup.gitconnected.com/path-aliases-with-typescript-in-node-js-230803e3f200
- The target package must define
exports
in it’spackage.json
- The module-alias config must resolve the proper package path
- This is tricky when working in monorepos and importing an alias of another package in the monorepo
- e.g. Using Yarn Workspaces, all TypeScript packages using
tsc
, running in dev without building will import the source files, but after build it will imports the compiled files - In this scenario, the module-alias should work for both use cases
- e.g. Using Yarn Workspaces, all TypeScript packages using
- This is tricky when working in monorepos and importing an alias of another package in the monorepo
.eslintrc.js
- For JavaScript files:
'import/resolver': {
node: {
moduleDirectory: ['node_modules', __dirname, 'src'],
},
},
- For TypeScript files:
'import/resolver': {
typescript: {
alwaysTryTypes: true,
project: `${__dirname}/tsconfig.json`,
},
},
- If using import/order, we might want to assign aliases to to a group:
'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.config.js
ornext.config.js
- resolve.modules
config.resolve.modules = ['node_modules', path.resolve(cwd, 'src')];
config.resolve.alias = {
...config.resolve.alias,
public: path.resolve(cwd, 'public'),
};
jest.config.js
- moduleDirectories
moduleDirectories: ['node_modules', 'src'],
moduleNameMapper: {
public: '<rootDir>/public',
}
.storybook/main.js