What solutions are available for resolving the devServer issue in webpack?

Any help or advice would be greatly appreciated. I have configured webpack and everything works in production mode, but the webpack-dev-server is not recognizing static files and is giving the error "Cannot get /". How can I resolve this issue? Thank you in advance for your assistance. Below is my webpack.config.js file:

const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
// const autoprefixer = require("autoprefixer");

const isProd = process.env.NODE_ENV === "production";
const isDev = !isProd;

const optimization = () => {
  const config = {
    runtimeChunk: "single",
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          priority: -10,
          chunks: "all",
        },
      },
    },
  };

  if (isProd) {
    config.minimizer = [
      new CssMinimizerWebpackPlugin(),
      new TerserWebpackPlugin(),
    ];
  }

  return config;
};

module.exports = {
  entry: path.resolve(__dirname, "src", "index.js"),
  mode: isProd ? "production" : "development",
  output: {
    path: path.join(__dirname, "build"),
    filename: "[name].[contenthash:8].js",
    chunkFilename: "[name].[contenthash:8].js",
    publicPath: "./",
  },
  devtool: isDev ? "source-map" : false,
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.vue$/,
        loader: "vue-loader",
      },
      {
        test: /\.(eot|ttf|woff|woff2)(\?\S*)?$/,
        loader: "file-loader",
        options: {
          name: "[name][contenthash:8].[ext]",
        },
      },
      {
        test: /\.(png|jpe?g|gif|webm|mp4|svg)$/,
        loader: "file-loader",
        options: {
          name: "[name][contenthash:8].[ext]",
          outputPath: "assets/img",
          esModule: false,
        },
      },
      {
        test: /\.s?css$/,
        use: [
          "style-loader",
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              esModule: false,
            },
          },
          "css-loader",
        ],
      },
    ],
  },
  plugins: [
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({
      filename: "[name].[contenthash:8].css",
      chunkFilename: "[name].[contenthash:8].css",
    }),
    new HTMLWebpackPlugin({
      template: path.join(__dirname, "src", "public", "index.html"),
      filename: "start-page.html",
      alwaysWriteToDisk: true,
      minify: {
        collapseWhitespace: isProd,
      },
    }),
    new CleanWebpackPlugin(),
  ],
  resolve: {
    alias: {
      vue: "@vue/runtime-dom",
    },
    extensions: ["*", ".js", ".vue", ".json"],
  },
  optimization: optimization(),
  devServer: {
    compress: true,
    port: 9000,
    hot: true,
    client: {
      overlay: true,
    },
  },
};

Below are the project folders: https://i.sstatic.net/JS3yW.png

Answer №1

Make sure to specify the publicPath in the devServer, as outlined in the documentation.

For more information, refer to the official documentation

module.exports = {
  //...
  devServer: {
    static: {
      directory: path.join(__dirname, 'public'),
    },
    compress: true,
    port: 9000,
  },
};

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

Enhancing a validation form with the 'onblur' event handler

Exploring the realm of JavaScript, I find myself intrigued by the concept of creating a validation form that activates upon clicking out of the input field. Implementing various techniques to integrate this feature into an existing form has been both chall ...

I find myself struggling to manage my javascript dependencies

Currently, I am utilizing NPM along with various angular packages. As per the tutorial on Basic Grid Part 1 at this link, I am encountering challenges. This is my file directory structure: D:/nodeStuff/uiGrid includes: node_modules uigrid.css uigrid.h ...

Ways to verify the presence of an item in a MonoDB array

My MongoDB model looks like this: const userSchema = new Schema = ({ name: { type: String }, company: [ companyId: { type: String, }, movies: [ { genre: { type: String, enum: [ ...

Navigate using React to a different HTML page based on certain conditions

After calling the fetch function, I am able to retrieve the correct token from the backend application. However, every time in this program, even if an incorrect token is retrieved, the program still navigates to StudentLobby (this should only happen when ...

In a REST api, what is the appropriate response for a property that is missing a value?

Is it better for a property with no value assigned to be returned as null, or should the REST API skip such properties entirely? Let's consider a user object example with first_name and last_name. (In the below example, last_name is not necessarily a ...

Perform multiple function invocations on a single variable using JavaScript

Is there a way to execute multiple functions on a single object in JavaScript? Maybe something like this: element .setHtml('test'), .setColor('green'); Instead of: element.setHtml('test'); element.setColor('gre ...

jQuery Issue DetectedSlight complication spotted with jQuery

I've encountered a peculiar problem with jQuery's contains function: HTML <span class="tag diaTags label label-info">Teststring<span data-role="remove"></span></span> JS When I directly use $('span.diaTags:contai ...

Developing instance members and methods in JavaScript

After encountering a challenge with creating "private" instance variables in JavaScript, I stumbled upon this discussion. Prior to posing my question, I wanted to provide a thorough overview of the problem. My goal is to showcase a complete example of corr ...

Having trouble combining different styles with Material-ui and Radium?

Trying to integrate Radium with Material-ui has presented a challenge. Attempting to apply multiple styles to a single Material-ui component results in no styling being applied. For instance, the following code fails to render any styling: <MenuItem st ...

Custom-designed background featuring unique styles

I have implemented the following code to create a continuous running banner: <style> #myimage { position: fixed; left: 0%; width: 100%; bottom: 0%; background:url("http://static.giga.de/wp-content/uploads/2014/08/tastatur-bild ...

Click the "Add" button to dynamically generate textboxes and copy the contents from each

I am working on a project where I have an Add button and 6 columns. Clicking on the Add button generates rows dynamically, which can also be deleted. My challenge is to copy the content of one textbox into another in 2 of the columns. This copying function ...

Tips for halting the live graph plotting based on a specific condition with canvas js

I have a piece of code that generates a live graph based on probabilities. I am looking for a way to stop the plotting process as soon as a specific condition is met. <script> window.onload = function () { var dps = []; // dataPoints var c ...

Clicking on a date in Vue.js Fullcalendar

My goal is to retrieve a date value from the onDateClick function of fullCalendar using vue.js and then pass this data to a prop that can be stored in my backend via Laravel. However, I am encountering various undefined errors no matter how I approach th ...

Learn the process of fetching checkbox values using JavaScript with this snippet

Is it possible to retrieve the name of the selected checkbox values/labels from the following code: <input id ="abc" value="abeexch" type ="checkbox"> <input id ="nam" value="suns" type ="checkbox"> If a checkbox is selected, how can I obtain ...

How can the data controller of a model be accessed within a directive that has been defined with "this"?

I'm struggling with accessing data using a directive, especially when I have defined my models like this: vm = this; vm.myModel = "hello"; Here is an example of my directive: function mySelectedAccount(){ return { restrict: 'A&ap ...

Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page wh ...

What is the best way to use a computed property as a style value for a component in Vue.js?

My component's template includes the following HTML element: .grid-item(:style="{ width: columnWidth, backgroundColor: 'blue' }") I want to dynamically set the width of this element using a computed property: computed: { columnWidth () ...

looking to retrieve the corresponding value of a specific array key

I am trying to determine the value of a complex array, but I keep getting values like 0,1,2,3,4,5 as answers. Here is the code snippet I am using to retrieve the state value of the array: var shardState = Object.keys(mydata.cluster.collections[collection ...

What is preventing me from accessing my session array in this.state.props from my mapStateToProps in React-Native Redux?

I am currently facing an issue with my Redux store setup. I am attempting to store an array of Session objects, where each Session object contains an array of Hand objects. However, when trying to access my store using `mapStateToProps`, none of the option ...

Instead of displaying a regular text box, the output unexpectedly shows "Printing [object HTML

There are some HTML and JavaScript files that I have. I've written some functions in my JavaScript file to save the values of different input fields. However, when I try to print the description, it just displays [object HTMLInputElement]. This mak ...