[英]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.