对于像./src/components/A.vue 这样的路径很容易做到这一点。 @/components/A.vue 比较棘手,因为您需要解析 @ 别名。
以下解决方案适用于两者。
要在路径中强制 .vue 扩展,请执行以下操作:
1. 安装eslint-plugin-import,它通过检查导入路径来扩展 eslint 的功能。还可以安装自定义路径解析器 - eslint-import-resolver-alias:
npm install eslint-plugin-import eslint-import-resolver-alias --save-dev
2. 然后,在您的 ESLint 配置文件(.eslintrc.js 或 package.json 等中的 eslintConfig 字段)中,添加以下内容:
// I'm using .eslintrc.js
module.exports = {
//...unimportant properties like root, env, extends, parserOptions etc
plugins: ["import"],
settings: {
"import/resolver": {
alias: {
map: [
["@", "./src"], //default @ -> ./src alias in Vue, it exists even if vue.config.js is not present
/*
*... add your own webpack aliases if you have them in vue.config.js/other webpack config file
* if you forget to add them, eslint-plugin-import will not throw linting error in .vue imports that contain the webpack alias you forgot to add
*/
],
extensions: [".vue", ".json", ".js"]
}
}
}
}
这里是 a repository with a working demo,它在导入中正确实现强制 .vue 路径。
还有来自 VSCode 的屏幕截图和来自npm run lint 的输出: