使用 Eslint 的 Vite.js 上的 Vue 3 — 无法解析模块 eslint 的路径(import/no-unresolved)

Del*_*con 14 javascript eslint vue.js eslintrc vite

我在 Vite.js 上使用 Vue 3 和 Eslint + Airbnb 配置。Airbnb 配置有一个规则eslint(import/no-unresolved),这很好,但 Eslint 不知道如何解析别名路径。

\n

我想对路径 \xe2\x80\x94 使用别名,例如:\nimport TableComponent from \'@/components/table/TableComponent.vue\'\xcb\x99

\n

环境是纯 JavaScript 的。

\n

我设法设置了我的vite.config.js应用程序可以解析这样的路径:

\n
import path from \'path\';\nimport { defineConfig } from \'vite\';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: [{\n        find: "@", replacement: path.resolve(__dirname, \'src\')\n      },],\n  },\n});\n
Run Code Online (Sandbox Code Playgroud)\n

Vue 应用程序的工作方式如下并正确解析导入路径,但 Eslint 不断报告错误:Unable to resolve path to module eslint(import/no-unresolved)

\n

我如何以及在哪里可以告诉 Eslint 如何解析别名?

\n

我已经尝试过:\ninstall eslint-plugin-import eslint-import-resolver-alias --save-dev

\n
// .eslintrc.js\n\n// ...\nextends: [\n    \'eslint:recommended\',\n    \'plugin:import/recommended\',\n    \'airbnb-base\',\n    \'plugin:vue/vue3-strongly-recommended\',\n],\n\nsettings: {\n    \'import/resolver\': {\n      alias: {\n        map: [\n          [\'@\', \'src\'],\n        ],\n      },\n    },\n  },\n
Run Code Online (Sandbox Code Playgroud)\n

但这是行不通的。

\n
\n

编辑:
\n解决了问题,如果您像我一样使用纯 JavaScript,请参阅已接受的答案。

\n

如果您使用的是 TypeScript,请查看Seyd 的回答是否可以帮助您。

\n

Sye*_*yed 17

这解决了我的项目中的问题TypeScript

npm install eslint-import-resolver-typescript
Run Code Online (Sandbox Code Playgroud)

eslint-import-resolver-typescript安装后

{
  // other configuration are omitted for brevity
  settings: {
    "import/resolver": {
      typescript: {} // this loads <rootdir>/tsconfig.json to eslint
    },
  },
}
Run Code Online (Sandbox Code Playgroud)

应添加到.eslintrc.js.

我的 tsconfig.json (删除不需要的设置)

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": false,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "types": ["vite/client", "node"],
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    "allowJs": true
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "exclude": ["node_modules"]
}
Run Code Online (Sandbox Code Playgroud)

检查这里的讨论:


Del*_*con 3

如果有人遇到这个问题,这适用于我的情况*:

settings: {
    'import/resolver': {
      alias: {
        map: [
          ['@', './src'],
        ],
      },
    },
  },
Run Code Online (Sandbox Code Playgroud)

*就我而言,Vue 的根目录是 'src' 目录,而 Eslint 的根目录高一级,因此它需要 './src' 路径。

非常感谢@https://github.com/aladdin-add 通过 github 问题给出的答案!