eslint-plugin-import 用于查看 ES Module 的导入和导出代码,避免文件门路和导入名称拼写错误的问题。

装置应用

  1. 装置

    npm install --save-dev eslint eslint-plugin-import
  2. 配置:.eslintrc

    • 举荐:

      {    "extends": ["plugin:import/recommended"],    "plugins": "eslint-plugin-import"}
    • TypeScript:

      {    "extends": [        "plugin:import/recommended",        "plugin:import/typescript"    ],    "plugins": "eslint-plugin-import"}

      ps:须要额定装置 @typescript-eslint/parsereslint-import-resolver-typescript

模块解析

咱们在引入 eslint-plugin-import 插件后常常会遇到模块无奈解析的问题。

Unable to resolve path to module '.../xxx'  import/no-unresolved

通常会呈现以下这几种状况。

  1. 引入了 jsx 或者 vue 模块时短少扩展名,ESLint 正告找不到模块;

    import Button from "./Button"; // Button.jsx// Unable to resolve path to module './Component'

    eslint-plugin-import 默认遵循 node 的模块解析形式,没有后缀名的模块会先查找是否有 .js 文件,没有的话查找是否有同名目录,查找该目录是否有 package.json 或 index.js。为了解决这个问题,咱们须要批改 eslint-plugin-import 默认解析器的扩展名配置。

    {    "settings": {        "import/resolver": {            "node": {                "extensions": [".js", ".jsx"]            }        }    }}
  2. 应用了 webpack 等打包工具的模块别名,ESLint 提醒找不到模块;

    import Button from "@/components/Button";

    如上文所述,eslint-plugin-import 默认遵循 node 的模块解析形式,而不反对 webpack 的别名。但 eslint-plugin-import 的模块解析是可扩大的。为了解决这个问题,咱们只须要装置依赖 eslint-import-resolver-alias,而后按如下形式配置:

    {  "settings": {    "import/resolver": {      "alias": {        "map": [["@", "./src"]],        "extensions": [".js", ".jsx"]      }    }  }}

    ps:map 的门路是绝对 IED 我的项目根目录的,如果 eslintrc 不在根目录下,倡议改用 js 来配置绝对路径(path.resolve(__dirname, 'src'))。

  3. 引入 jsx 之类非 js 扩展名的代码模块时不会进行依赖查看;

    // Component.jsxexport const name = "Component";// index.jsimport Component from "./Component.jsx";

    如上所示的代码,Component 并没有导出默认模块,而 index.js 却以默认模块的形式引入,实践上 eslint 应该正告 No default export found in imported module "./Component.jsx"/

    呈现这个问题是因为 eslint-plugin-import 默认只会校验 js 扩展名的模块代码,能够按如下配置调整模块反对的扩展名:

    {    "settings": {        "import/extensions": [".js", ".jsx"]    }}