Let ESLint automatically write and remove ES6 import
statements for you
Install ESLint either locally or globally.
$ npm install eslint --save-dev
If you installed eslint
globally, you have to install known-imports plugin globally too. Otherwise, install it locally.
$ npm install eslint-plugin-known-imports --save-dev
You have to be running ESLint in "fix" mode (in your editor, or with --fix
on the command line)
The plugin provides enhanced versions of existing ESLint rules like no-undef
and no-unused-vars
You tell the plugin which imports should be auto-generated when you use certain names in your code, typically by providing a known-imports.json
or known-imports.yaml
file in your project root directory
"plugins": ["known-imports", ...],
"extends: ["plugin:known-imports/recommended-react", ...]
"plugins": ["known-imports", ...],
"extends: ["plugin:known-imports/recommended", ...]
Then you provide a known-imports.json
or known-imports.yaml
file in the project root directory, see the next section for its format
Here's an example known-imports.json
that may give you the idea:
{
"View": "react-native",
"isEmpty": "lodash",
"moment": {"module": "moment", "default": true},
"fmap": {"module": "lodash/fp", "name": "map"},
"withExtractedNavParams": {"module": "utils/navigation", "local": true},
}
The keys are the names used in your code (that would be reported as unknown by no-undef
or react/jsx-no-undef
)
Just specify the module
you're importing the name from:
"View": {"module": "react-native"}
would generate:
import {View} from 'react-native'
There's also an equivalent shorthand:
"View": "react-native"
Add "name": "originalName"
:
"fmap": {"module": "lodash/fp", "name": "map"}
would generate:
import {map as fmap} from 'lodash/fp'
Add "default": true
:
"moment": {"module": "moment", "default": true}
would generate:
import moment from 'moment'
Add "local": true
to distinguish project-local imports eg:
"MySharedComponent": {"module": "components/MySharedComponent", "default": true, "local": true}
You only need to distinguish local imports if you want to follow the convention where nonlocal imports come first, followed by a blank line and then local imports
If you don't want to use the plugin:known-imports/recommended
or plugin:known-imports/recommended-react
presets, you can specify rules individually in your .eslintrc
To avoid duplicate warnings, you'll always want to disable the existing ESLint rule that the plugin rule enhances, eg
"rules": {
"no-undef": "off",
"known-imports/no-undef": "error"
}
The ESLint rules provided by the plugin are:
known-imports/no-unused-vars
(enhances no-unused-vars
)
By default this rule removes any unused import
that it finds. To restrict it to only remove known imports, set "onlyRemoveKnownImports": true
eg
"rules": {
"no-unused-vars": "off",
"known-imports/no-unused-vars": ["error", {"onlyRemoveKnownImports": true}]
}
eslint-plugin-known-imports is licensed under the MIT License.