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:

1
2
3
4
5
6
7
8
9
10
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:

1
'@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.

1
2
3
4
5
6
7
8
9
10
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?

1
2
3
4
5
6
7
8
9
10
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!