如何将项目相关导入与 eslint 结合使用?

mik*_*ana 6 javascript eslint webpack eslintrc

注意:我已经检查了 StackOverflow 上的各种答案,但它们主要关注 ES6 导入根本不起作用或 ReactJS 特定问题。这个问题专门询问与项目相关的导入。

我有一个包含以下内容的文件:

import { AUTH_COOKIE } from "./use-auth";
Run Code Online (Sandbox Code Playgroud)

当我用 eslint 检查时一切正常。

$ npx eslint lib/file2.js

/home/mike/Code/myapp/frontend/lib/file2.js

(no errors)

Run Code Online (Sandbox Code Playgroud)

但是我想使用项目相关的导入,例如:

import { AUTH_COOKIE } from "lib/use-auth";
Run Code Online (Sandbox Code Playgroud)

这会导致错误:

$ npx eslint lib/file1.js

/home/mike/Code/myapp/frontend/lib/file1.js
  1:29  error    Unable to resolve path to module 'lib/use-auth'  import/no-unresolved
Run Code Online (Sandbox Code Playgroud)

不过,Webpack 仍然可以正确构建项目 - 这只是一个 eslint 错误。

我已检查了import/no-unresolved 的文档,但看不到指定项目根目录的设置。

  • 根据上面的内容,使用文件相对导入进行导入工作正常
  • 从node_modules导入模块工作正常
  • .ts文件还具有与项目相关的工作导入

如何使用 eslint 'import/no-unresolved' 进行项目相对导入?

我的 。eslintrc在下面。

// Note eslintrc does not use booleans to turn features on/off!
/*eslint-disable no-unused-vars*/
const OFF = 0,
  WARN = 1,
  ERROR = 2;

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
    jest: true,
  },
  extends: [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:import/react",
    "plugin:import/warnings",
    "plugin:jsx-a11y/recommended",
    "plugin:react-hooks/recommended",
    "prettier",
    "plugin:import/errors",
    "plugin:import/warnings",
    "plugin:import/typescript",
  ],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: "module",
  },
  plugins: ["react"],
  rules: {
    // Current standard (according to pro-types maintainer) is to use TS for this
    "react/prop-types": OFF,

    // Deprecated - see https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/accessible-emoji.md
    "jsx-a11y/accessible-emoji": OFF,

    // Deprecated - see https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-onchange.md
    "jsx-a11y/no-onchange": OFF,

    // Removing autofocus doesn't help accessibility and harms experience for other users
    "jsx-a11y/no-autofocus": OFF,

    // next.js 'Link' element uses anchors without href attribute.
    // The compiled result will have an href, so this is safe to ignore.
    // (they'll be added later) https://nextjs.org/docs/api-reference/next/link
    "jsx-a11y/anchor-is-valid": OFF,

    // Don't worry if we leave an `import { log }` somewhere
    "no-unused-vars": WARN,

    // We want to be able to type an apostrophe in some body copy without a React warning
    "react/no-unescaped-entities": OFF,
  },
};
Run Code Online (Sandbox Code Playgroud)