I'm starting a new vue.js project so I used the vue-cli tool to scaffold out a new webpack project (i.e. vue init webpack
).
As I was walking through the generated files I noticed the following imports in the src/router/index.js
file:
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello' // <- this one is what my question is about
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello
}
]
})
I've not seen the at sign (@
) in a path before. I suspect it allows for relative paths (maybe?) but I wanted to be sure I understand what it truly does.
I tried searching around online but wasn't able to find an explanation (prob because searching for "at sign" or using the literal character @
doesn't help as search criteria).
What does the @
do in this path (link to documentation would be fantastic) and is this an es6 thing? A webpack thing? A vue-loader thing?
UPDATE
Thanks, Felix Kling for pointing me to another duplicate stackoverflow question/answer about this same question.
While the comment on the other stackoverflow post isn't the exact answer to this question (it wasn't a babel plugin in my case) it did point me in the correct direction to find what it was.
In the scaffolding that vue-cli cranks out for you, part of the base webpack config sets up an alias for .vue files:
This makes sense both in the fact that it gives you a relative path from the src file and it removes the requirement of the .vue
at the end of the import path (which you normally need).
Thanks for the help!
Answers
The @
sign in the import path (@/components/Hello
) is a special alias defined in the webpack configuration generated by vue-cli.
By default, the @
alias points to the src
directory of your Vue.js project. This allows you to import modules using a relative path from the src
directory without having to worry about the directory structure.
For example, if you have a component located at src/components/Hello.vue
, you can import it in other files using @/components/Hello
instead of the full relative path ../../components/Hello
. This makes the import paths cleaner and more readable.
The @
alias is defined in the webpack configuration (build/webpack.base.conf.js
or similar) using the resolve.alias
option:
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
}
This alias configuration allows webpack to resolve @
to the src
directory when processing import statements.
So, in short, the @
alias in Vue.js projects generated by vue-cli is a webpack feature that provides a convenient way to import modules relative to the src
directory. It improves code readability and maintainability by simplifying import paths.