This article is going to be a quick tutorial on how to set webpack aliases in a Vue JS project. This article is going to assume that your project has been created using Vue Cli. If it makes sense for your project, I highly recommend using it.
Webpack aliases are a great way to simplify imports in your Vue JS projects. Instead of specifying long paths, we can instead use a short alias and webpack will generate the full path when we build/run our project.
How To Set Up Webpack Aliases in Vue
To start, open up the vue.config.js file in the root directory of your project. If this file does not exist, create it.
Then, post in the following snippet:
const path = require('path');
module.exports = {
configureWebpack: {
resolve: {
alias: {
//aliases go here
},
},
}
Take a look at the alias property of the configureWebpack object. This is where we are going to put all of our aliases.
A webpack alias looks something like the following:
'@c': path.resolve(\_\_dirname, 'src/components')
What we can do now is fill out this alias object with a few paths that we want to alias. To create an alias, simply create a property which will be the name of your alias. In this example, all of the aliases will be prefixed with the @ symbol, but you could pretty much do whatever you want. The value must be set to the path for the directory you want to alias.
const path = require('path');
module.exports = {
configureWebpack: {
resolve: {
alias: {
'@c': path.resolve(\_\_dirname, 'src/components'),
'@m': path.resolve(\_\_dirname, 'src/mixins'),
},
},
}
Awesome, we have aliases. How can we use them in our Vue components?
import MyComponent from '@c/MyComponent.vue'
import MyMixin from '@m/MyMixin'
export default {
name: 'Home',
components: {
MyComponent,
},
mixins: [MyMixin],
};
Wow, isn’t that awesome. Look at how short those import statements are. No we don’t have to worry about typing out a bunch of long, unmaintainable paths.
I hope you enjoyed this content. If you liked this, considering checking out my article about How To More Efficiently Pass Down Props in Vue JS or this other article about How To Import All Vuex Modules Automatically.
Have fun!
The post Webpack Aliases in Vue JS appeared first on Remote Dev Daily.
Top comments (1)
wasn't working, this post covers some problems
stackoverflow.com/questions/553099...
the "extensions: ['.js', '.vue', '.json']" was the missing part for me i think