Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force .vue extension in all imports using eslint?

In VS Code with Vetur (the extension for working with Vue), "Go to definition" will not work on component imports where there's no .vue extension at the end (Vetur FAQ link)

I was wondering if there's an eslint rule that will force the user to always provide an extension when using an import statement in .vue files?

Examples:

  • ✔️ 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.

like image 548
walnut_salami Avatar asked Nov 02 '19 13:11

walnut_salami


1 Answers

It's easy to do this for paths like ./src/components/A.vue. It's trickier for @/components/A.vue because you need to resolve the @ alias.

The below solution works for both.

To force .vue extensions in paths, do this:

1. Install eslint-plugin-import, which extends functionality of eslint by linting import paths. Also install with a custom path resolver - eslint-import-resolver-alias for it:

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

2. Then, in your ESLint config file (.eslintrc.js, or eslintConfig field in package.json etc), add this:

// 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"]
      }
    }
  }
}

Here's a repository with a working demo that implements forcing .vue path in imports correctly.

And a screenshot from VSCode and output from npm run lint:

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

like image 176
walnut_salami Avatar answered Sep 21 '22 17:09

walnut_salami