webpack Aliases

We don't use VueJS at my day job, but I try to take every opportunity I can to get my hands dirty with it on side projects and for fun.

After generating a vue-cli webpack project you'll notice that the ES6 import statements begin with the @ in the provided example components.

importHelloWorldfrom"@/components/HelloWorld";

The @ symbol in this case references the ./src directory. So instead of having to use ../ to eventually find the module we're looking for, we get this nice little @lias to do the monotonous work for us. Nice and clean!

We use React heavily at Musicbed and love it to pieces. Our application is fairly robust and I felt something like this could be really helpful to our team. I began digging into ways to introduce aliases into our custom webpack config.

The first place I looked was in the webpack boilerplate vue-cli provides and found this little bit of code in webpack.base.conf.js:

The code above essentially tells webpack that when it's doing it's business and comes across an import with the @ symbol, look in the src directory and continue doing it's thing.

This got me thinking about our codebase and how I could leverage aliases even more than just the one for src. Along with React components, we also use Redux actions, reducers, and have a handful of other things I thought would be nice to have easier access to.

What about VSC?

Let's circle back around to my buddy Tj's original tweet. The code I've shown above is for webpack to understand what to do with our aliases. Our editor is pretty clueless so we have to tell it as well.

In VSC we can add a file called jsconfig.js to our project root and do some config'n.

IntelliSense now works as it should and your editor can see what's inside the imported file and do it's auto-complete magic.

This solution also comes with one caveat I'm aware of. At the time I'm writing this, VSC won't auto-complete the imported path while you're typing it. Bummer! I believe there is an issue to hopefully fix this in upcoming builds so we should be okay!