【问题标题】:How to force .vue extension in all imports using eslint?如何使用 eslint 在所有导入中强制 .vue 扩展?
【发布时间】:2020-02-28 11:19:53
【问题描述】:

在带有Vetur(使用 Vue 的扩展名)的 VS Code 中,“转到定义”不适用于末尾没有 .vue 扩展名的组件导入 (Vetur FAQ link)

我想知道是否有 eslint 规则会强制用户在 .vue 文件中使用 import 语句时始终提供扩展名?

例子:

  • ✔️ 这行得通:

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

    在 VS Code 中右键单击 HelloWorld 并按 Go to definition 会转到 HelloWorld.vue 文件。

  • ❌这不是:

    import HelloWorld from '@/components/HelloWorld'
    

    如果您在HelloWorld(最左侧)上按Go to definition,VS Code 只会将光标移动到您刚刚右键单击的HelloWorld。预期的行为是我们移动到 HelloWorld.vue 文件。

【问题讨论】:

    标签: vue.js eslint vetur


    【解决方案1】:

    对于像./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.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"]
          }
        }
      }
    }
    

    这里是 a repository with a working demo,它在导入中正确实现强制 .vue 路径。

    还有来自 VSCode 的屏幕截图和来自npm run lint 的输出:

    【讨论】:

      【解决方案2】:

      你需要配置eslint-plugin-importvue文件设置强制,只需在eslint config中添加这条规则

      "import/extensions": ["error", "ignorePackages", { "vue": "always" }],
      

      【讨论】:

      • 这不适用于.vue 文件。查看我在原始问题下的评论。我已经提交了一个问题。它可以按预期适用于 .js 文件
      • @ArturTagisow 我在我的项目中使用这个规则并且它有效。我正在使用版本^2.18.2
      • 嗯,您是使用 Vue 和 JavaScript 还是 TypeScript?我正在使用 TS
      • @ArturTagisow JS,给我时间在 TS 上测试一下
      • 我最近不得不重新审视这个。将它与 webpack 别名(在我原始问题的路径中的 @)一起使用是一场噩梦,我无法让它在 Vue CLI 项目中工作。我还创建了github.com/benmosher/eslint-plugin-import/issues/1533。您可能需要安装 eslint-import-resolver-webpack 并在那里定义 webpack 别名,请参阅:github.com/benmosher/eslint-plugin-import/tree/master/resolvers/…
      猜你喜欢
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2021-07-11
      • 2017-07-04
      • 2020-04-03
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多