Define specific import rules for files within your Typescript project. Adapted and enhanced from VSCode's code-import-patterns
yarn add --dev eslint-plugin-ts-import
- Provide import patterns that restrict imports of certain files based on location.
- Ensure imports meet the expected guidelines within your repo.
- Adapted from VSCode's rule
code-import-patterns
. - Works with configured
paths
from yourtsconfig.json
- Provide custom eslint messaging for each pattern if needed.
- Useful in monorepos and most Typescript projects which utilize incremental builds.
// .eslintrc.js
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
rules: {
'ts-import/patterns': [
'error',
{
// these rules apply to any files which are within the src/services directory
target: '**/src/services/*/**',
// allow any imports to node_modules. We confirm that the node_module exists in case the use of paths / absolute imports is used so that
// we can tell the difference
modules: true,
// allow imports of node core modules? defaults to true. if false, imports like fs, path, stream will cause an error
node: true,
allowed: [
// anything in src/services/{service}/** may import config `import config from 'config'`
'config',
// anything in src/services/{service}/** may import from core `import someModule from 'core/someModule'`
'core/**',
// run target.replace(arr[0], arr[1]) to build pattern
// any service may import from itself - so src/services/rest-api/** may always import from `src/services/rest-api/**`
// whether using relative or absolute imports. However it will not be able to import from `../api-client/**` or `services/api-client/**`
[/.*\/src\/services\/([^/]*)\/.*/, '**/src/services/$1/**'],
// allow any imports whether relative or absolute as long as they are not higher than /src/services
[/(.*\/src\/services).*/, '$1/**'],
// this rule without the above rule would only allow the files to import themselves or higher and would restrict `../`
'./**',
],
message:
'Optional custom message to display when violated',
},
],
},
plugins: ['ts-import']
}
- While originally utilizing custom logic, we since borrowed the resolving method used by eslint-import-resolver-typescript.