Enhance User Experience: Implement Asynchronous Loading of Vue Components in Laravel 5.6 using laravel-mix and webpack

Laravel 5.6.21
NPM 6.1.0
Node 10.5.0
Webpack 3.12.0

Seeking guidance on how to correctly set up laravel-mix, webpack, and babel to enable lazy-loading of vue components using the technique outlined in Lazy Loading Routes.

In particular, implementing stage-2 (es2018 ?) syntax such as:

const Foo = () => import('./Foo.vue')

Encountering errors when attempting to compile with laravel-mix where statements resembling the above syntax trigger an error message like:

 Syntax Error: Unexpected token (1:24)

 1 | const Dashboard = () => import("Pages/Account/Dashboard.vue");

   |                         ^

Understanding that laravel-mix utilizes Babel for transpilation and realizing that 'syntax-dynamic-import' is needed, I created a .babelrc file with the following content:

{
  "plugins": [
    "syntax-dynamic-import"
  ]
}

Having no luck with the .babelrc configuration, I also experimented with an eslint config file containing:

module.exports = {
  plugins: ["vue"], 
  extends: ["plugin:vue/recommended", "prettier"],
  parserOptions: {
    "parser": "babel-eslint",
    "ecmaVersion": 7,
    "sourceType": "module",
    "ecmaFeatures": {
      "globalReturn": false,
      "impliedStrict": false,
      "jsx": false,
      "experimentalObjectRestSpread": false,
      "allowImportExportEverywhere": false
    }
  }
}; 

Lastly, here are the dependencies listed in package.json:

  "devDependencies": {
    "@vue/test-utils": "^1.0.0-beta.24",
    "babel-core": "^6.26.3",
    "babel-eslint": "^8.2.3",
    "babel-loader": "^7.1.5",
    "babel-plugin-syntax-dynamic-import": "^6.18.0",
    "babel-plugin-transform-imports": "^1.5.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "babel-preset-vue-app": "^2.0.0",
    "cross-env": "^5.2.0",
    "eslint": "^4.19.1",
    "eslint-config-prettier": "^2.9.0",
    "eslint-loader": "^2.0.0",
    "eslint-plugin-html": "^4.0.1",
    "eslint-plugin-vue": "^4.5.0",
    "expect": "^22.0.3",
    "jsdom": "^11.5.1",
    "jsdom-global": "^3.0.2",
    "laravel-mix": "^2.1.14",
    "less": "^3.5.3",
    "less-loader": "^4.1.0",
    "mocha": "^4.0.1",
    "mocha-webpack": "^1.0.1",
    "stylus": "^0.54.5",
    "stylus-loader": "^3.0.1",
    "vue-loader": "^13.7.2",
    "vue-style-loader": "^4.1.0",
    "vue-template-compiler": "^2.5.13",
    "vue-test-utils": "^1.0.0-beta.8",
    "webpack": "^3.12.0",
    "webpack-auto-inject-version": "^1.1.0"
  },

Any suggestions or assistance in resolving this issue would be highly appreciated.

Answer №1

In my experience, I have been utilizing the following configuration in my .eslintrc.json file:

"extends": [
    "eslint:recommended",
    "plugin:vue/recommended"
],
"plugins": [
    "vue"
],
"parser": "vue-eslint-parser",
"parserOptions": {
    "parser": "babel-eslint",
    "ecmaVersion": 8,
    "ecmaFeatures": {
        "jsx": true
    },
    "sourceType": "module"
},

It is also important to double-check the path of your dynamic import function, such as

const Dashboard = () => import("Pages/Account/Dashboard.vue");
. It might be more appropriate to use a relative path like
const Dashboard = () => import("./Pages/Account/Dashboard.vue");
.

Answer №2

Encountering an issue with `scss splitting` in Vue and utilizing `mix.scss()` simultaneously can lead to Laravel mix generating a CSS file with manifest JS content, which is considered a bug by the community. This bug is attributed to Webpack and is expected to be fixed in webpack 5. However, if you solely implement code splitting in Vue and import the default `app.scss` file into the main Vue component without scoping it, each component will receive the styling correctly.

// resources/js/components/app.vue
<template>
 <!-- Main Vue Component -->
</template>

<script>
// Main Script
</script>

<style lang="scss">
 @import '~@/sass/app.scss';
</style>

In this scenario, the `webpack.mix.js` file should exclude the `mix.scss` function to only run a single app.js file. You can refer to my setup below:

// webpack.mix.js
const mix = require('laravel-mix')
mix.babelConfig({
 plugins: ['@babel/plugin-syntax-dynamic-import'] // make sure to install -D
})

mix.config.webpackConfig.output = {
 chunkFilename: 'js/[name].bundle.js',
 publicPath: '/'
}

mix
 .js('resources/js/app.js', 'public/js')
 .extract(['vue'])
 .webpackConfig({
 resolve: {
 alias: {
   '@': path.resolve('resources/') // for using relative paths correctly
 }
 }
})

Here's a snippet from the `package.json` file (including essential dev dependencies):

{
       "@babel/core": "^7.8.7",
        "@babel/plugin-syntax-dynamic-import": "^7.8.3",
        "@babel/preset-env": "^7.8.7",
        "laravel-mix": "^4.1.4",
}

I trust that implementing these adjustments will help resolve the issue at hand.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a brainstorming tool using Nuxt.js

Apologies if this question is a bit broad. I'm interested in how to create a mindmap similar to the image provided below using Nuxt.js. The boxes should allow users to input text, but they don't need to be draggable - just stationary. I'm se ...

Encountering an issue stating: "[Vuetify] v-ripple can only be applied to block-level elements" while attempting to deploy on Heroku platform

Lately, I've been working on developing an app using Rails 6 with a mix of Vue and Vuetify for the front end. Everything runs smoothly on my local machine. However, as soon as I attempt to deploy it on Heroku, I encounter this error in the debug conso ...

Struggling to display sub-categories correctly within the Categories Dropdown menu

Attempting to display sub-categories in the Categories Dropdown list In my code, I aim to display category and sub-category under the Category in the Products table. This is how my categories table looks: 1. public function up() { Schema::create(&apos ...

Tips for passing two parameters to an event in JavaScript

I'm a bit confused on how to send 2 parameters for event listening in JavaScript and Vue.js. I am trying to edit input data when the keyup event is equal to 13 (enter), but I am unsure of how to send the event along with the value. When I try to send ...

Issues with padding and margin not displaying correctly at different screen sizes

I'm currently utilizing tailwindCSS and am facing an issue with adjusting the size of buttons based on screen sizes. I want the buttons to appear small with minimal vertical padding on desktop screens, and bigger with increased vertical padding on mob ...

Encountering a problem: The function _ctx.openNote is not recognized as a function when attempting to click on a note for viewing

I started with my notepad app from the ground up, which can be found on this link: Issues with data bind in vue.js and events The problem I encountered was that I couldn't click on the note from NoteList.vue to view the details. There seems to be a d ...

Learn how to effectively display checkboxes in an HTML form with Vue configuration

new Vue({ el: '...', data: { checkeditems: [] } }) <div v-for="item in instituteModel" v-if="instituteModel.length > 0"> <input type="checkbox" id="item.id" value="item.inst_name" v-model="checkeditems"/> </div&g ...

Inertiajs - Seamlessly transition to a different page within the same environment

Is there a way to navigate between pages on the client side in Laravel and InertiaJS without using inertia.visit()? I am curious about how to switch pages solely within the client, without having to communicate with the server. Can props be specified fro ...

What is the process of utilizing marked plugins within a Vue3 project?

I attempted to integrate the marked plugin into my Vue.js applications. After installing [email protected], I did not encounter any issues during compilation. However, when I viewed the contents in the browser, nothing appeared. My Vue project was built u ...

failure of text to display in d3.append

Having trouble displaying a tooltip on a rectangle in d3js. The tooltip renders, but the text doesn't show up. After researching similar issues, I discovered that I cannot directly append 'text' to a 'rect' element. I tried addin ...

Tips for asynchronously modifying data array elements by adding and slicing

I am facing an issue in my vuejs application where I need to modify an array of items after the app has finished loading. My current setup looks like this: var n = 100; var myData = []; function loadMovies(n){ // async ajax requests // add items to ...

The search bar in Laravel is encountering an Uncaught ReferenceError with AJAX

I'm attempting to create a real-time search bar for my products list, but I keep encountering an error in my console Uncaught ReferenceError: data is not defined at HTMLInputElement.<anonymous> (produits:243) at HTMLDocument.dispatch (jquery-2.2 ...

Creating a dynamic webpage using the MVC design pattern within a Docker container

I am facing a challenge with my dotnet core application that has authorization. Due to company policy restrictions, Bearer tokens cannot be stored on the front-end. To work around this, I want to utilize an MVC Controller. However, the application is built ...

Retrieving Vue component properties as a data type

I'm facing a dilemma with my Vue components. I want to extract the props from one component and use them as a type instead of a value in another component. Specifically, I have a component where I need to take in an array of props from a different com ...

Troubleshooting Issue: Difficulty with color--text not displaying in Vue 3/Vuetify 3 Integration

Today, I attempted to set up Vuetify with Vue3 for the first time. Most things seem to be working fine: components are being imported correctly, and classes like "text-center" are functioning as expected. However, I have noticed that props such as "dark" ...

Vue.js encountering an issue of receiving null for the JSON data upon the initial loading phase

Currently, I am expanding my knowledge on vue.js and experimenting with calling a json file to parse the data. Although everything seems to be functioning as intended, whenever I refresh the page, there is a momentary blank screen before the data loads. In ...

display different vue component based on screen size

I am in search of a method to implement responsive components in Vue.js (Nuxt). I have developed this mix-in but encountering an error: export const mediaQuery = { data() { return { breakpoints: { sm: 576, md: 768, lg: ...

Enhancing data management with Vuex and Firebase database integration

Within my app, I am utilizing Firebase alongside Vuex. One particular action in Vuex looks like this: async deleteTodo({ commit }, id) { await fbs.database().ref(`/todolist/${store.state.auth.userId}/${id}`) .remove() .then ...

Vue 3 Single Page Application. When selecting, it emits the language and the contentStore does not update the content exclusively on mobile devices

My Vue 3 Single Page Application is built on Vite 4.2 and TypeScript 5.02. When I click to select a language, it emits lang.value and in the parent component App.vue, contentStore should update the content. It works flawlessly on my Linux Ubuntu desktop i ...

Switch the custom audio control button on and off within a v-for loop

I have implemented a unique audio play/pause button in my Vue app for a list of audios. Here is how it looks: <div v-for="(post, p) in post_list"> ... ... ... <v-avatar v-if="!is_played" color="#663399" ...