【问题标题】:How to change eslint settings to understand absolute import?如何更改 eslint 设置以了解绝对导入?
【发布时间】:2018-05-08 13:30:32
【问题描述】:

我使用 create-react-app 并且我想使用来自 ./src 的绝对导入。

作为 Dan Abramov recommended 我添加了 .envNODE_PATH=src 并且它有效。

但我的 eslint 不明白该模块已经存在。我收到错误 import/no-unresolvedimport/extensions

这是我的 eslint 配置:

module.exports = {
parser: 'babel-eslint',
extends: 'airbnb',
rules: {
    'react/no-did-mount-set-state': 'off',
    'import/no-extraneous-dependencies': 'off',
    'no-use-before-define': 'off',
    'arrow-body-style': 'off',
    // uncommit on developing
    'no-console': 'off',
    'no-debugger': 'off',
  },
  globals: {
    browser: true,
    fetch: true,
    serviceworker: true,
    describe: true,
    it: true,
    expect: true,
    document: true,
  },

};

当然,如果 vscode 可以通过 'src' 为我提供建议,那将是一件好事。

【问题讨论】:

  • 你只是想隐藏 eslint 警告,还是想让它检测路径是否正确?
  • 当然我可以把这些规则关掉,但可能有机会继续找文件。
  • 在你不想被eslint-ed的文件开头使用/* eslint-disable rulename */
  • 你的问题正是我的答案。非常感谢。

标签: javascript reactjs create-react-app


【解决方案1】:

你需要使用eslint-plugin-import:https://github.com/benmosher/eslint-plugin-import

并在.eslintrc中配置你的eslint设置

module.exports = {
  ...   
  "settings": {
    "import/resolver": {
      "node": {
        "paths": ["src"]
      }
    },
  },
}

然后,您可以使用从src 文件夹导入。

例如,如果你有src/components/MyComponent.jsx,你会这样写:

import MyComponent from 'components/MyComponent.jsx';

【讨论】:

  • 仍然有同样的问题,应用此之后.. 任何更新?
  • 这对我也不起作用,Rehan,但确实如此:"settings": { "import/resolver": { "node": { "moduleDirectory": ["node_modules", "src/"] } } }
  • 我在根目录下导入文件时遇到问题。怎么解决?
  • 嗨。到目前为止,我这样做了,一切都很好,但是当涉及到解决 @material/core 时,它​​无法解决它
【解决方案2】:

有点晚了,但上面的答案并没有解决我的问题。经过一番研究,我发现 this article 使它对我有用。

安装 eslint-plugin-import

npm i -D eslint-plugin-import

jsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

eslintrc.json

{
  "extends": ["react-app", "plugin:import/errors", "plugin:import/warnings"],
  "settings": {
    "import/resolver": {
      "node": {
        "moduleDirectory": ["node_modules", "src/"]
      }
    }
  }
}

【讨论】:

    【解决方案3】:

    您正在扩展 airbnb 的 eslint 配置,其中包括 eslint-plugin-import,默认启用以下规则:no-absolute-path

    见: https://github.com/benmosher/eslint-plugin-import/blob/HEAD/docs/rules/no-absolute-path.md

    您可能需要调整更多规则。

    【讨论】:

    • 我阅读了该链接,但由于我是 rust/wasm/js 的新手,所以对我来说有点困惑。如果我有import loadWasm from '/Users/tymac/web/src/lib.rs';,这是否意味着我需要先在 eslintrc.json 中定义路径?如果可能的话,您能否以我的路径为例添加您的答案?
    • 作为相对路径快速修复,我只是将 lib.rs 文件复制到当前目录中,该目录比 import 语句高一级。因此import loadWasm from '../lib.rs';。不过能知道怎么符合airbnb eslint就好了。
    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 2020-08-12
    • 2020-09-30
    • 2013-08-11
    • 1970-01-01
    • 2020-05-27
    • 2020-02-19
    • 2018-12-24
    相关资源
    最近更新 更多