denorm's avatar

Laravel Mix Dynamic Imports

Looks like dynamic imports will finally work with Mix: https://laravel-news.com/using-dynamic-imports-with-laravel-mix

I have followed this post exactly (including installing @babel/plugin-syntax-dynamic-import with npm install --save-dev, a step not mentioned in the post).

In my .babelrc I have:

{
  "plugins": [
    "@babel/plugin-syntax-dynamic-import"
  ]
}

In my vue-router file I try to dynamically import a component:

const Login = () => import(/* webpackChunkName: "LoginComponent" */ '../views/Login.vue');

But always get an error:

ERROR in ./resources/assets/js/router/index.js 7:9
Module parse failed: Unexpected token (7:9)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| 
| var Login = function Login() {
>   return import(
|   /* webpackChunkName: "LoginComponent" */
|   '../views/Login.vue');
 @ ./resources/assets/js/app.js 26:0-30 146:13-19 208:10-16 218:18-24 220:0-6
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

I've also tried importing directly inside the routes, but get the same error:

{
      path: '/login',
      name: 'login',
      component: () => import(/* webpackChunkName: "login" */ '../views/Login.vue'),
},

Any ideas?

Thanks :)

EDIT:

I've resolved the initial problem- seems to have been due to my npm dependencies. Just need to make sure laravel-mix is requiring latest versions of webpack and acorn. I found help in this thread: https://github.com/webpack/webpack/issues/8656#issuecomment-456010969

However, there's still an issue with laravel-mix not outputting CSS when using extract(), so I still cannot go ahead with dynamic imports in my project: https://github.com/JeffreyWay/laravel-mix/issues/1856

0 likes
5 replies
michapietsch's avatar

@denorm I just read about it in the issues.

The workaround at the moment is to compile CSS outside of the Mix config in which you use extract().

For Tailwind I use a simple npm script. For CSS processing with Mix someone suggested to add another Mix config file, e.g. webpack.css.mix.js and add it to the npm scripts. etc.

2 likes
denorm's avatar

Hi @michapietsch thanks for following up on this! In the end, it was much more important for me to dynamically import certain components and resources like language files, rarely used views, etc. Building these components into separate, dynamically loaded downloads reduced my initial build size considerably.

So, I just ended up removing extract(). Although extract is nice, the benefit I gained from dynamic imports was greater than having a separate vendors file. (Besides, I've found that the vendors file is updated quite frequently.)

I'll wait until the next version of webpack & laravel-mix to go back to using extract.

Thanks so much!

1 like

Please or to participate in this conversation.