Laravel tips: set resolve alias in Laravel mix

Kay Gosho - Apr 25 '18 - - Dev Community

This is not exactly about Laravel but Webpack, neverthless, I thought I should have set this at the beginning of my project.

Prerequisites

Developing with

  • Laravel 5.4
  • webpack (Laravel mix)

Problem

I used to relatively specify path to a file in any .js files:

// resources/assets/vue/components/Deep/Path/To/Component.vue

import FooComponent from '../../FooComponent.vue'
Enter fullscreen mode Exit fullscreen mode

This is hard to understand, and if I change the directory structure I have to change every path.

...and just looks ugly.

Solution

Add the following config at the beginning of webpack.mix.js.

// webpack.mix.js

const { mix } = require('laravel-mix')

mix.webpackConfig({
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': __dirname + '/resources/assets/js'
    },
  },
})

// ...config follows
Enter fullscreen mode Exit fullscreen mode

Then, we can import like this:

// resources/assets/vue/components/Deep/Path/To/Component.vue

import FooComponent from '@/components/FooComponent'
Enter fullscreen mode Exit fullscreen mode

I found vue-cli uses this config. It set resolve alias @ to src by default.

https://github.com/vuejs-templates/webpack/blob/f21376d/template/build/webpack.base.conf.js#L40

Hope this config comes to default of Laravel Mix.
I am wondering I would send a PR...

Refs

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player