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'
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
Then, we can import like this:
// resources/assets/vue/components/Deep/Path/To/Component.vue
import FooComponent from '@/components/FooComponent'
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...
Top comments (10)
This will not work on the latest laravel-mix. laravel-mix.com/docs/4.0/extending...
It is working for me in the latest laravel-mix:
Thanks! This is the cleanest way.
mix.extend('exampleConfig', new class {
webpackConfig(webpackConfig) {
webpackConfig.resolve.extensions.push('.js', '.vue', '.json'); // you don't need this on v4
webpackConfig.resolve.alias = {
'vue$': 'vue/dist/vue.esm.js',
'@': __dirname + '/resources/assets/js'
};
}
});
and lastly, call it on last: mix.exampleConfig();
Thank you for pointing out!
use this laravel-mix.com/index.php/extensio...
I get an npm compile error using either solution:
"Invalid CSS after "...load the styles": expected 1 selector or at-rule, was "var content = requi"
The referenced sass file uses several @import statements.
In addition, I am using mix v2 and PHPStorm 2019.3. I don't understand the solution offered above for PHPStorm, since Mix already includes a webpack.config.js file at root. How is one supposed to integrate the suggested code with what is already in that config file? I've seen a number of proposed solutions to this question, but I haven't gotten anything to work. Any suggestions would be appreciated.
This seems to break the IDE (phpstorm) though. You can no longer click on a component name and you get an underline error "module is not installed"
See here for a solution to that issue:
gist.github.com/nachodd/4e120492a5...
Oh really, I have never used PHPStorm. Thank you for pointing out.