Encountering issues with Vue routing while utilizing webpack. The main page is functional, however, subpaths are resulting in

Before implementing webpack, my vue routing was functioning properly. However, I encountered several loader issues and decided to use webpack. After setting up webpack, the main page loads correctly, but all of my routes now result in a 404 error. I have already attempted various solutions that were commented out, but none worked. I suspect there may be a problem with my webpack configuration file, but I am unable to identify it. Any suggestions or assistance would be greatly appreciated. Thank you for your time.

App.vue

<template>
  <div class="base-app">
    <div class="mapbox" id="mapbox">
      <router-view />
    </div>
  </div>
</template>

<script>
// import Login from './components/login.vue';
// import Tract from './components/tract.vue';

export default {
  name: "App",
  // components: {
  //   Login,
  //   Tract
  // }
};
</script>

router.js

import { createWebHistory, createRouter } from "vue-router";
import Index from "./components/index.vue";
import Login from "./components/login.vue";
import Tract from "./components/tract.vue";

const routes =  [
  {
    path: "/",
    component: Index
  },
  {
    path: "/login",
    component: Login
  },
  {
    path: "/tract/:id",
    component: Tract
  }
];


const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

main.js

import { createApp } from 'vue';
import App from './App.vue';
// import login from './components/login.vue';
// import tract from './components/tract.vue';
import router from './router.js';

import "./assets/styles/normalize.css";
import "./assets/styles/app.css"; 

const app = createApp(App);
// app.component('login', login);
// app.component('tract', tract);
app.use(router);
app.mount('#app');

webpack.config.cjs

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

module.exports = {
  entry: {
    main: "./src/main.js",
  },
  output: {
    filename: 'main.bundle.js',
    path: path.resolve(__dirname, 'dist/')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.vue$/,
        loader: "vue-loader",
      },
      {
        test: /\.s?css$/,
        use: [
          "style-loader",
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              esModule: false,
            },
          },
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                plugins: () => [autoprefixer()],
              }
            },
          },
          "sass-loader",
        ],
      },
      {
        test: /\.m?js/,
        resolve: {
          fullySpecified: false,
        },
      }
    ],
  },
  plugins: [
    new VueLoaderPlugin(),
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: "[name].[contenthash:8].css",
      chunkFilename: "[name].[contenthash:8].css",
    }),
    new htmlWebpackPlugin({
      template: path.resolve(__dirname, "public", "index.html"),
      favicon: "./public/favicon.ico",
    }),
  ],
  resolve: {
    extensions: [ '.tsx', '.ts', '.js', '.vue' ],
    alias: {
        'vue': '@vue/runtime-dom'
    }
  },
  devtool: 'source-map'
};

vue.config.cjs

module.exports = {
  devServer: {
    disableHostCheck: true,
    devMiddleware: {
      writeToDisk: false
    }
  }
}

package.json

{
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "scripts": {
    "startdev": "webpack-dev-server --mode development --config ./webpack.config.cjs",
    "start": "NODE_ENV=production webpack --config ./webpack.config.cjs"
  },
  "dependencies": {
    "@aws-amplify/ui-vue": "^3.1.20",
    "aws-amplify": "^5.3.3",
    "axios": "^0.22.0",
    "bootstrap": "4.6.0",
    "chart.js": "^4.4.0",
    "core-js": "^3.34.0",
    "jquery": "^3.6.0",
    "mapbox-gl": "^2.6.0",
    "popper.js": "^1.16.1",
    "postcss-loader": "^7.3.3",
    "vue": "^3.0.0",
    "vue-chartjs": "^5.2.0",
    "vue-router": "4"
  },
  "devDependencies": {
    "@babel/core": "^7.23.5",
    "@babel/preset-env": "^7.23.5",
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "autoprefixer": "^10.4.16",
    "babel-loader": "^9.1.3",
    "clean-webpack-plugin": "^4.0.0",
    "css-loader": "^6.8.1",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.5.4",
    "mini-css-extract-plugin": "^2.7.6",
    "postcss": "^8.4.32",
    "sass": "^1.69.5",
    "sass-loader": "^13.3.2",
    "source-map-loader": "^4.0.1",
    "style-loader": "^3.3.3",
    "vue-loader": "^17.3.1",
    "vue-template-compiler": "^2.7.15",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  },
}

Answer №1

Consider deleting the webpack.config.js file and utilizing only the vue.config.js file instead.

package.json

{
  "name": "marc-diff-checker",
  "version": "1.0.0",
  "private": true,
  // scripts removed for brevity
}

vue.config.js

'use strict';
// vue configuration code, some parts omitted for conciseness

src/main.js

// main.js script content, excluding certain sections

src/router.js

// router setup in JavaScript, key parts excluded for clarity

src/App.vue

<template>
  // App component template with CustomHeader, v-main, and CustomFooter
</template>

<script>
// Script tag for handling events and methods in the App.vue component
</script>

<style lang="scss">
  /* Styling section for the App component */
</style>

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

update-post-thumbnail wp-ajax return false

I have been attempting to utilize the media manager within Wordpress. I am using the post editor outside of the admin area, allowing users to create posts with a featured image. I have used the _wp_post_thumbnail_html function to display the image or provi ...

Using HTML5 and an ASP.NET web method to allow for file uploads

My attempt to upload a file to the server using an HTML5 input control with type="file" is not working as expected. Below is the client-side JavaScript code I am using: var fd = new FormData(); fd.append("fileToUpload", document.getElementById(&ap ...

Displaying the selected item right at the center of the Flatlist in React Native

I need to ensure that the item selected in the FlatList is always centered. The chosen item should have a different style compared to the others. <FlatList data={items} style={styles.listStyle} ...

Organizing layers with Leaflet's layerGroup controls

I am working with a series of Leaflet FeatureGroups, each made up of GeoJSON layers. These FeatureGroups have similar concepts but need to be kept separate for control purposes. I also require the ability to toggle all FeatureGroups on and off simultaneous ...

The message sent back by Django Rest Framework is: "a legitimate integer must be provided"

I have integrated a react form within my Django application, supported by the rest framework in the backend. When I submit the form without entering any value in the integer field, I encounter the following error message from the rest API: "a valid integer ...

Mocking Ext.Ajax.request in ExtJS 4.2.1 is a process of em

When it comes to frontend unit testing using Jasmine, one of the challenges I faced was mocking all the requests in my application. Luckily, I have already tackled a method to mock all my proxies successfully: proxy: appname.classes.proxy.ProxyNegotiator ...

Testing the functionality of an Express.js application through unit testing

I'm currently working on adding unit tests for a module where I need to ensure that app.use is called with / and the appropriate handler this.express.static('www/html'), as well as verifying that app.listen is being called with the correct p ...

Analyzing past UTC date times results in a peculiar shift in time zones

When I receive various times in UTC from a REST application, I encounter different results. Examples include 2999-01-30T23:00:00.000Z and 1699-12-30T23:00:00.000Z. To display these times on the front end, I use new Date(date) in JavaScript to convert the ...

What is the best way to create a random key using a factory function?

I am working on a function that generates objects, and I would like to be able to specify the key for the object as a parameter. However, when I try to do this, the function does not recognize the parameter properly and sets its name as the key instead. h ...

What is the significance of having a timer in a Redux reducer to prompt a re-rendering process?

Encountered some unusual behavior that I need to understand better Here is the code for my reducer. Strangely, the component linked to the redux state does not re-render with this code. Despite confirming through developer tools that the state updates cor ...

I keep encountering an error that says "ReferenceError: localStorage is not defined" even though I have already included the "use

I have a unique app/components/organisms/Cookies.tsx modal window component that I integrate into my app/page.tsx. Despite including the 'use client' directive at the beginning of the component, I consistently encounter this error: ReferenceErr ...

What's the reason behind the malfunction of this code on Chrome?

After recently installing Mobiscroll, I have been using the date scroller feature with the following code to manage the textbox. <script type="text/javascript"> $(function() { // create a datepicker with default settings $("#begi ...

Safari has trouble with AJAX cross-origin requests, while Chrome and Firefox handle them without issue

I am developing a Shopify app that utilizes script tags and requires an ajax call to our server to retrieve necessary information about the shop. While everything seemed to be functioning correctly, my colleague pointed out that it was not working on his i ...

Show React compilation errors

Whenever I used to start React as per their tutorial, it would show compile errors in this specific scenario. However, after setting up a webpack configuration for a React project, if there are compilation errors, the page simply remains blank. Is there ...

The instance does not have a definition for the property or method "names" that is being referenced during rendering

Currently, I'm working on developing a CRUD application using Vue.js and Firebase. However, I've encountered an error that I can't seem to resolve: [Vue warn]: Property or method "names" is not defined on the instance but referenced during r ...

Encountering 'Element not found' error when automating Flight Booking on MakeMyTrip.com using Selenium WebDriver, specifically while trying to select a flight after conducting a search

Currently in the process of automating the flight booking feature on MakeMyTrip.com using Selenium WebDriver. I have implemented separate classes for Page Object Model (POM) and TestNG. The code successfully automates the process up to the point of clicki ...

Exploring the World of Popper.js Modifiers

Within our React and Typescript application, we integrate the react-datepicker library, which utilizes popper.js. Attempting to configure PopperModifiers according to the example provided here: . Despite replicating the exact setup from the example, a typ ...

What methods can I use to prevent an image from moving and trigger a specific action with the press of a key?

I'm currently teaching myself web programming and also working on improving my C++ skills. However, I am facing a challenge with Javascript. My main question is regarding how to create an "if statement" based on the location of an image. I am in the ...

Discovering the magic of nesting maps in React-Native without the need for

I am currently developing a react-native app that retrieves its data through an API. I am working on implementing a new feature where the information is grouped by date. The JSON data structure sent by the API looks like this: { "channel_count" ...

Is it feasible to preserve the HTML form content data even after refreshing the page?

Can someone offer a suggestion that doesn't involve using Ajax? I'm wondering if there is a way to achieve this using JavaScript/jQuery or some other method. Here's my issue: When submitting a page, the action class redirects back to the sa ...