如何使用eslint强制在所有导入中使用.vue扩展名?

10
在使用Vetur(用于处理Vue的扩展程序)的Visual Studio Code中,“转到定义”功能将无法在组件导入中起作用,其中结尾没有.vue扩展名(Vetur FAQ link)。
我想知道是否有一种eslint规则可以强制用户在.vue文件中使用import语句时始终提供扩展名?
例如:
  • ✔️ This works:

      import HelloWorld from '@/components/HelloWorld.vue'
    

    Right clicking on HelloWorld and pressing Go to definition in VS Code wil take you to the HelloWorld.vue file.

  • ❌ This doesn't:

    import HelloWorld from '@/components/HelloWorld'
    

    If you press Go to definition on HelloWorld (leftmost), VS Code will just move the cursor to the HelloWorld you just right clicked. Intended behavior is that we move to the HelloWorld.vue file.

2个回答

8

对于像./src/components/A.vue这样的路径,这很容易实现。但对于@/components/A.vue,更加棘手,因为您需要解析@别名。

以下解决方案适用于两者。

要强制在路径中包含.vue扩展名,请执行以下操作:

1. 安装eslint-plugin-import,它通过linting导入路径扩展了eslint的功能。同时,安装带自定义路径解析器的插件 - eslint-import-resolver-alias

npm install eslint-plugin-import eslint-import-resolver-alias --save-dev

2. 接着,在您的 ESLint 配置文件中(如:.eslintrc.jspackage.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"]
      }
    }
  }
}

这里有一个工作示例的代码仓库它正确实现了在导入中强制使用 .vue 路径。

以下是VSCode的屏幕截图和npm run lint的输出:

eslint errors regarding missing .vue path showing up in vscode problems view and in terminal output after running npm run lint


4
您需要配置eslint-plugin-import,以在vue文件上设置force,只需在eslint配置中添加此规则即可。
"import/extensions": ["error", "ignorePackages", { "vue": "always" }],

这对于.vue文件不起作用。请查看我在原始问题下的评论。我已经提交了一个问题。但是它对于.js文件按预期工作。 - user10706046
@ArturTagisow 我在我的项目中使用了这个规则,它很有效。我正在使用版本 ^2.18.2 - Farnabaz
嗯,你是用JavaScript还是TypeScript来使用Vue的?我是用TS。 - user10706046
1
最近我不得不再次回顾这个问题。在使用webpack别名(在我的原始问题中路径中的@)时,这是一场噩梦,我无法在Vue CLI项目中使其正常工作。我还创建了https://github.com/benmosher/eslint-plugin-import/issues/1533。你可能需要安装`eslint-import-resolver-webpack`并在那里定义webpack别名,请参见:https://github.com/benmosher/eslint-plugin-import/tree/master/resolvers/webpack - user10706046
@ArturTagisow 你好,大佬,你是如何解决这个问题的?我已经配置了 Node 和 Webpack 插件用于 eslint-import,但我的还是无法正常工作。 - Wenfang Du
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接