Struggles with eliminating Mix from a Laravel-Vue hybrid project

My goal is to streamline the process of adopting new features or releases by removing Laravel Mix from my project. I want to avoid using Mix's syntax or plugins and eliminate the need to contain everything within the webpackConfig method.

I have successfully created a Webpack configuration for styles and assets. However, I am facing an issue with the vue-loader not importing styles from Vue single file components in a static .html file. When I use the html-webpack-plugin, everything functions correctly. But when I include the .js bundle in a static .html file, the styles fail to load. My aim is to get it working in a static .html file to replicate the behavior of a PHP blade file.

Below is a simplified version of my setup:

webpack.config.js

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { VueLoaderPlugin } = require("vue-loader");
const htmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: {
        main: "./src/main.js",
    },
    output: {
        filename: 'js/[name].js',
        path: path.resolve(__dirname, 'dist')
    },
    resolve: {
        extensions: ['.js', '.vue'],
        alias: {
            "vue$": "vue/dist/vue.common.js"
        }
    },
    module: {
        rules: [
            {
                test: /\.((c|sa|sc)ss)$/i,
                use: [
                'vue-style-loader',
                MiniCssExtractPlugin.loader,
                'css-loader', 'postcss-loader', 'sass-loader'
            ],
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader'],
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
        ],  
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'css/[name].css',
        }),
        new htmlWebpackPlugin({
            template: path.resolve(__dirname, "public", "index.html")
        }),
        new CleanWebpackPlugin({
            cleanStaleWebpackAssets: false,
            verbose: true
        }),
        new VueLoaderPlugin()
    ],
};

main.js

import Vue from "vue";
import App from "./App.vue";

new Vue({
    render: (h) => h(App),
}).$mount("#app");

App.vue

<template>
  <div id="app">
    <div class="nav">
        Test nav
    </div>
  </div>
</template>

<style lang="scss">
.nav {
    padding: 30px 0 100px 0;
    font-family: sans-serif;
}
</style>

index.html

(used to generate another index.html with html-webpack-plugin)

👉 with this one everything works


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Vue app</title>
</head>

<body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
</body>

</html>

index.html (static file)

👉 this one doesn't load the .css files

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>

<body>
    <div id="app"></div>
    <script src="dist/js/main.js"></script>
</body>

</html>

What I've tried

  • Not using html-webpack-plugin during the build (no change)
  • Using a different alias for $vue: (
    vue$: "vue/dist/vue.runtime.esm.js"
    ) (no change)
  • Not using mini-css-extract-plugin (the css wouldn't load even with the html-webpack-plugin)

In Laravel Mix, styles are loaded within <style> tags and not in separate .css files, which is not a problem for me.

Answer â„–1

After studying this response on the Stack Overflow thread How to switch from laravel mix to pure Webpack? I was able to extract the setup details for a new Laravel Mix project with minimal configuration.

Mix.listen('configReady', function (config) {
  RegExp.prototype.toJSON = RegExp.prototype.toString;
  console.log(JSON.stringify(config));
});

I discovered that Laravel Mix utilizes distinct sets of loaders for css files originating from Vue compared to other css/scss files.

Although I didn't directly copy their setup due to redundancy, I managed to devise a simplified setup that achieves the same results:

// [...]
module: {
  rules: [
    {
      test: /\.vue\.css$/, // specific to vue css
      use: [
        'style-loader',
        'css-loader',
        'postcss-loader',
        'sass-loader'
      ]
    },
    {
      test: /\.((c|sa|sc)ss)$/i,
      exclude(modulePath) {
        // excluding vue css
        return modulePath.includes('.vue');
      },
      use: [
        {
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: '../',
          },
        },
        'css-loader', 'postcss-loader', 'sass-loader'
      ]
    },
    // [...]
  ]
}

While I'm uncertain if this is the most effective method for loading css in Vue applications, I can now replicate the same setup as in the original project.

Edit 01/28/21

For handling scss files, it's necessary to update the initial test in this manner:

test: /\.vue\.((c|sa|sc)ss)$/i, // only vue css

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

Breaking circular dependencies in JavaScript is a common challenge that developers face when

Having encountered a circular dependency issue between certain JS files, I am seeking steps to resolve it. Q1: Is repositioning the require function an appropriate solution? One suggested approach to resolve this issue is to move the require() statement ...

Guide on inputting Vue component in props

<template> <v-dialog width="auto" v-model="isShown" transition="dialog-bottom-transition" > <v-card> <v-card-title v-if="title"> {{ title }}</v-card-title> ...

Unit testing in Angular JS is crucial, especially when testing functions in services that do not return any values

Apologies if this has been asked before, but I couldn't find a solution to my issue. I need to create tests for a service within an Angular JS application. The main function of the service returns and is used as an external method. There are also a ...

What is the best way to hide the div when scrolling to the top?

Is there a way to hide the circle once it's scrolled to the top? Currently, I can scroll the circle to the top but it remains visible. Upon further exploration, I found that clicking on the circle scrolls it to the top and then on a second click, it f ...

The URL switches back and forth from "localhost:8100" to "localhost:8100/some-route" while displaying a blank white screen

After working on my ionic app without any issues, I restarted my computer only to find that when I tried to run the project again, I was met with a blank white screen on both the browser and device. Even when I reverted back to an earlier branch, the URL c ...

Are you looking to convert this JSON using underscore or any other JavaScript utility tool?

Looking at this JSON data: [{"target": "mydata.12.2", "datapoints": [[763.7, 1368821100], [762.1, 1368821160], [223.11, 1368821220], [886.54, 1368821280], [112.3, 1368821340]]}] I need to strip the first key and square brackets so it appears like this: ...

Changing the size of a responsive navigation bar with React and adjusting it based on the window.scrollY position switches between collapsed and un

I'm struggling to create a responsive navbar that automatically adjusts its size once it surpasses the height of the navbar (currently set at 80px). However, when I scroll to around the 80px mark, it starts flickering between the collapsed and expande ...

Combine multiple key values from an array of objects into a single array

I have a set of key and value pairs that I need to filter based on whether the values are in an array or not, and then combine them into a single array. const holiday_expenses = { food: [{name: "abc", place: "xyz"}], travel: [{name: ...

jQuery Click event not responding on the default Android Mobile Browser for anchor elements

Having trouble triggering a click event on a link element, as the title suggests. Here is the relevant part of the HTML structure: <!-- Table markup here.. --> <td class="text-center"> <a class="text-danger"><i class="fi-trash" ari ...

When using res.render to send results, redundant lines are displayed

I feel like I must be missing something really obvious, but for the life of me I cannot figure out what it is. All I want to do is list the documents in a MongoDB collection in a straightforward manner. I am working with nodejs, mongoose, and Jade (althoug ...

Is there a way to retrieve the information from the v-text-field without using the v-model directive?

<div v-for="i in parseInt(questionCount)" :key="i"> <v-layout> <v-flex xs6 offset-3 mt-15" > <label for=""> Enter question number {{index}}:</label> <v-text-fi ...

Connect Bootstrap Tabs to a pagination system (Backward Forward)

<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://m ...

Tips for updating a value in a React TextField using handleChange function

After clicking a button, I need to dynamically set a value in this textfield: <TextField fullWidth inputProps={{ maxLength: 75 }} key="nomeSocial" id="outlined-basic" label="Nome Social" name="nomeSocial&qu ...

Optimal Strategies for Handling Slugs with Laravel and Vue Router

I am working on a Laravel and Vue application. Specifically, I have developed a single-page application using Vue for a section called "shop". Within this shop, there are 3 subpages: "about", "products", and "contact". In my routes.php file: Route::get(& ...

Exploring the Differences Between JQuery Ajax Page Fragment Retrieval with Find and Filter

I am currently testing out the following Ajax code for a form. $('body').on('submit','#sign-in', function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr('action'); ...

Tips for resizing user-uploaded images to fit the required dimensions outlined in the design draft using CSS or JavaScript

Hey everyone! I'm facing an issue but my English isn't great. I'll do my best to explain it thoroughly, and if anything is unclear, please feel free to let me know! So here's the problem: today there's a block for users to upload p ...

Transferring information from JSON to HTML

Recently, I came across this handy design tool within our service that helps generate Gauge charts by simply adding a specific div class to the desired pages. <div class="gauge" id="g0" data-settings=' { "value": ...

Transforming the shopping cart with redux-saga

Hey there! I've been working on implementing a shopping cart feature using redux-saga. The current code seems to be functioning properly, but I have some concerns about the way I'm handling the cart state. It looks like I might be mutating the ca ...

Steps for converting a file with JSON objects to a JSON array

I have a JSON file with multiple objects stored in a single file that I need to convert into a JSON array using JavaScript. My main objective is to create a CSV file from this data. Here is an example of the file content: { Name:"nom1", Cities:[&apos ...

Uncertainties surrounding the use of JSON data versus a JavaScript object

As a newcomer to programming, I have ventured into Stack Overflow and W3schools to enhance my skills. Recently, I created a small project for educational purposes. One dilemma is bothering me - is the JSON file I generated actually in proper JSON format o ...