Autocompletion for webpack path aliases in PhpStorm when using Laravel Mix

Published on November 16th, 2019

After a long time, I wanted to show you another quick tip. At the moment I work a lot with InertiaJS, built by Jonathan Reinink. It allows you to create fully client-side rendered, single-page apps. It makes a lot of fun, but there was one thing that has always been annoying me. At least if you're using Laravel Mix.

If you take a look at the demo project PingCRM, there is a file called webpack.mix.js. You will find something like this:

webpack.mix.js
webpackConfig({
    output: { chunkFilename: 'js/[name].js?id=[chunkhash]' },
    resolve: {
      alias: {
        'vue$': 'vue/dist/vue.runtime.esm.js',
        '@': path.resolve('resources/js'),
      },
    },
  })

This allows you to import components directly from the resources/js directory like so:

import Logo from '@/Shared/Logo';

What sucks now is, that you can not use PhpStorm autocompletion when you hover over the path, press cmd and click to jump to that file as you always do. This is because PhpStorm doesn't know how to resolve that.

The solution

But there is a solution of course. And it's quite easy.

Create a separate webpack file and extract that webpack configuration to that file. You end up something like this:

webpack.config.js
const path = require('path')

module.exports = {
    output: { chunkFilename: 'js/[name].js?id=[chunkhash]' },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.runtime.esm.js',
            '@': path.resolve('./resources/js'),
        },
    },
}

The only thing you have to do now is to tell Laravel Mix to use that webpack configuration instead of the inline-configuration. You should end up with this in your webpack.mix.js:

webpack.mix.js
const mix = require('laravel-mix');
const config = require('./webpack.config');

mix.webpackConfig(config);

The last step is to tell PhpStorm there is a webpack configuration that can be used. Because PhpStorm only accepts webpack configuration in this case, the above steps have been necessary. 

Go to the settings and define your new created webpack.config.js file there and you're done. It takes a little bit of time until PhpStorm recognizes it.

If everything worked paths like '@/Shared/Logo' should now be resolved by PhpStorms autocompletion and let you jump directly into that file.

Bobby Bouwmann and I are writing a book called "Laravel Secrets".
You will learn everything about the undocumented secrets of the popular Laravel framework. You can sign up using the form below to get early updates.
      Visit laravelsecrets.com to get more information.