[英]How to change eslint settings to understand absolute import?
我使用 create-react-app,我想使用./src
的绝对导入。
正如 Dan Abramov 所建议的那样,我添加了带有.env
NODE_PATH=src
的 .env 并且它有效。
但是我的 eslint 不明白该模块已经存在。 我收到错误import/no-unresolved
和import/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-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';
有点晚了,但上述答案并没有为我解决问题。 经过一番研究,我发现这篇文章对我有用。
安装 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/"]
}
}
}
}
您正在扩展 airbnb 的 eslint 配置,其中包括eslint-plugin-import
,它默认启用以下规则: no-absolute-path
。
请参阅: https : //github.com/benmosher/eslint-plugin-import/blob/HEAD/docs/rules/no-absolute-path.md
除此之外,您可能需要调整更多规则。
这是一个快速修复,而不是最佳解决方案。
Omar Baharets 的回答启发了我这个解决方案。
如果您将airbnb
插件与eslint
一起使用,并且此错误是由该插件引起的,您可以简单地禁用给出错误的规则 ( import/no-unresolved
),如下所示:
//.eslintrc.js
module.exports = {
...,
rules :{
...,
'import/no-unresolved': 'off',
}
}
对于那些试图让它与 Vite 导入别名一起工作的人来说,@guillaume-jasmin 的回答的以下轻微修改对我有用。 我们的项目使用@
作为我们的src
目录的别名,导入插件不喜欢它,因为它需要一个实际的目录。 为了解决这个问题,我修改了vite.config.js
以将我们的src
目录别名为src
。 这允许我们进行导入,例如import SomeComponent from "src/components/SomeComponent"
。 以下是代码中的配置更改(我们将 Vite 用于 Vue 2 应用程序):
// vite.config.js
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, '/src'),
'src': path.resolve(_dirname, '/src'),
}
}
})
然后是 ESLint 配置:
// eslintrc.js
module.exports = {
settings: {
'import/resolver': {
node: {
paths: [path.resolve(__dirname)]
}
}
}
}
我在那里留下了 @import 别名,这样我们就可以在@
标记文件时逐渐迁移文件(我们只在更改的文件上运行 ESLint)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.