eslint-plugin-preferred-import
An ESLint plugin for checking import path with typescript. This rule reads your paths config in tsconfig.json and checks your import path that it is correct. And even if incorrect, try to Auto Fix.
Installation
You’ll first need to install ESLint:
npm i eslint --save-dev
Next, install eslint-plugin-preferred-import
:
npm i eslint-plugin-preferred-import --save-dev
Usage
ts-import
rule
If your project is based on Typescript, choice Here’s a suggested ESLint configuration:
{
parser: '@typescript-eslint/parser', // Should be used ts-eslint parser
plugins: [..., 'preferred-import'], // Add 'preferred-import' next to old plugins
overrides: [
...,
// Add rules into overrides
{
files: ['src/**/*.{ts,tsx}'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: ['./tsconfig.json']
},
rules: {
'preferred-import/ts-imports': 'error'
}
}
],
}
js-imports
rule
On the other hand, if your project is based on Javascript, choose Here’s a suggested ESLint configuration:
const path = require('path')
module.exports = {
plugins: [..., 'preferred-import'], // Add 'preferred-import' next to old plugins
rules: {
...,
// Add your rule config to the rules, resolveAlias should be same value with webpack alias
'preferred-import/js-imports': ['error', {
'resolveAlias': {
'utils': path.resolve(__dirname, 'src/utils'),
'reducer$': path.resolve(__dirname, 'src/reducer'),
}
}]
}
}
Supported Rules
-
ts-imports
: Check for replaceable paths based on basePath, paths field in tsconfig.json. Auto-fixable -
js-imports
: Check for replaceable paths based on rules config. Auto-fixable
License
BSD License