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.
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.
.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
:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With