issue with webpack-dev-server not refreshing after changes to HTML or Sass files

Here is the layout of my project:

\root    
   \webpack.config.js
   \public
     \ index.html
     \ ...
     \ css
     \ directives
     \ views   
     \ dist (webpack output)
       \app.js
       \ index.html
       \ app.js.map   
       \ style.css
       \ style.css.map

Whenever I use webpack-dev-server and launch it from /root, the app loads successfully. However, changes to sass or html files do not trigger a reload. What could be causing this issue in the webpack config?

To launch webpack, use the following command:

$ cd root
$ webpack-dev-server

This is the content of Webpack.config.js:

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

const webConfig = {
  entry: path.join(__dirname, 'public', 'js', 'app'),
  output: {
    path: path.join(__dirname, 'public', 'dist'),
    filename: 'app.js'
  },
  resolve: {
    modules: [__dirname, 'node_modules'],
    extensions: ['.js'],
    enforceExtension: false,
  },
  devtool: 'source-map',
  devServer:{
    contentBase: 'public/',
    publicPath: 'public/'
  },
  module: {
    loaders: [
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?modules,localIdentName=[name]__[local]--[hash:base64:5]!sass-loader'
        }),
        exclude: /node_modules/
      },
      {
        test: /\.html$/,
        loader: "raw-loader" // loaders: ['raw-loader'] is also perfectly acceptable.
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({filename: 'style.css', allChunks: true}),
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
};

module.exports = webConfig;

Answer №1

https://medium.com/@johndoe/webpack-deep-dive-into-the-mysterious-parts-f4e52438ebc2

When you use the "inline" option, you activate live reloading for the entire page. On the other hand, enabling the "hot" option provides Hot Module Reloading, which attempts to reload only the component that has changed instead of refreshing the entire page. If both options are passed, webpack-dev-server will first attempt HMR when a source change occurs. If that doesn't succeed, it will resort to reloading the whole page.

To incorporate these features into your webpack.config file, try adding the following:

devServer:{
    contentBase: 'public/',
    publicPath: 'public/',
    inline: true,
    hot: true,
  },

Additionally, consider calling a script from your package.json file like this:

...
scripts: {
   "watch": "webpack-dev-server --progress --colors --hot --inline",
}
...

Answer №3

To incorporate the feature, simply include watchContentBase: true within your devServer configuration

Pause the ongoing task and refresh the script

devServer: {
        contentBase: path.join(__dirname, 'public'),
        port: 9000,
        open:true,
        liveReload: true,
        watchContentBase: true,
      },

Answer №4

Consider removing HtmlWebpackPlugin from your project. Instead, utilize webpack-dev-server or webpack serve which can automatically detect the HTML file located in the ./public directory.

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

Cannot use Axios instance in Next.js due to error stating 'Localstorage is not defined'

I am currently working on a React app and have created an Axios component that I would like to reuse: import axios from 'axios' import dynamic from 'next/dynamic' const baseUrl = 'http://127.0.0.1:8000/' const axiosInstan ...

Having trouble importing images in React and passing them as a prop?

I'm attempting to import images, place them into an array, and then pass that array to a prop in a component to display different images. However, after passing the array to the component, the items accessed from the array are showing as undefined, pr ...

There are no markers or popups currently displayed on the map

Utilizing the ngx-leaflet plugin for leaflet, I have established the base layers and integrated a listener for the leafletMapReady event. Within my handler, I attempted to add both a marker and a customized popup. The handler code is displayed below: init ...

Updating variable values using buttons in PHP and Javascript

I've implemented a like/unlike button along with a field displaying the number of likes. The code below uses PHP and HTML to echo the variable that represents the total number of likes: PHP-HTML: <span>likes: <?php echo $row['likes&apo ...

Vue.js is throwing an error because it cannot find the property or method "blah" when referencing it during rendering

Can you explain why Vue 2 throws an error indicating that a prop is not defined, even though it is statically defined in the parent template? Note: This error does not occur when I include the JavaScript code within the .vue file's script tag instead ...

"Upon refreshing the browser, an Angular map loses its positioning and appears blank

I have implemented a LeafLet map in my Laravel 9 system, which is functioning properly with some exceptions. Here's how it looks like: https://i.stack.imgur.com/kcuVr.jpg The code in the controller (CompetitionsMapController.php) is as follows: ...

What is the best way to run a JavaScript function once another function has finished executing?

I am looking to ensure that a JavaScript function runs only after another one has finished executing. Here is the code I currently have: $(window).load(function(){ $('#dvLoading').fadeOut(2000); }); window.addLoadEvent = function() { $('#p ...

Issues with npm @material-ui/core Button and TextField functionality causing errors and failures

I'm currently working on a React project and decided to incorporate the material-ui framework. After creating a component that includes a textfield and a button, I've encountered an issue where I can't interact with either of them as they s ...

Error: Axios header not refreshing automatically in React. User must manually refresh the page

After logging in, I want to update the JWT token in the header before redirecting to the home page. Login.tsx ... const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.curr ...

What is the best way to automatically adjust the size of this HTML Menu to match the width of its

I am in the process of converting a Drupal 6 theme to Drupal 7 and I'm encountering some difficulties with this particular section. Below is the HTML code snippet: <ul id="nav" class=" scaling-active scaling-ready"> <li><a href="/demos ...

Tips for monitoring multiple values in a Vue 3 script setup

Within my code, I currently have a watcher set up like this (inside <script setup>): const form = reactive({ body: '', image: '' }) watch(() => form.image, () => { console.log(form.image) }) I am looking to enh ...

Would it be considered bad practice to utilize ng-init for executing a function in the controller upon the view being loaded?

For easier testing, I have started initializing my controllers using ng-init. So in my controller, you'll find code like this: $scope.initiate = function () { myResource.makeXhrRequest(); } And in my view, it looks like this: <div data-ng-i ...

Is it possible for the filter with the new date() function to accept formats other than yyyy-mm-dd?

After receiving a response from mydatepicker in the specific format below: { "isRange":false, "singleDate":{ "date":{ "year":2022, "month":5, "day":13 }, "jsDate": ...

Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process i ...

Postman seems to be functioning correctly while AXIOS is encountering issues

I've encountered a strange issue with my MERN app. When I use Postman to send a PUT request to my API, it successfully updates both the API and MongoDB. However, when performing the same action on the front-end, the API does not update even though the ...

What causes material-ui to consume excessive amounts of space?

My React project is being bundled using webpack, with a dependency on material-ui for the following components: material-ui/Dialog material-ui/styles/getMuiTheme material-ui/styles/MuiThemeProvider material-ui/FlatButton material-ui/TextField The webpack ...

Retrieving and submitting text in a NodeJS environment

I'm attempting to retrieve text from an API that only provides a string of text ((here)), but I am encountering difficulties in displaying it accurately. When I try to post it, the output shows as [object Response], and the console.log is not showing ...

Guide on how to load just the content section upon clicking the submit button

Here is an example of my code: <html> <head> <title>Test Loading</title> </head> <body> <div id="header"> This is header </div> <div id="navigation" ...

Having trouble with Javascript fetch() not receiving the correct JSON data from the local server

My Django backend is serving JSON data, but I'm encountering some unexpected results. When using curl 127.0.0.1:8000/posts/, the response includes: [ { "title": "This is a title", "body": "Body :)", "pub_da ...

Every time I try to read a file using JavaScript, I keep running into the error: "Uncaught TypeError: fs.readFile is not a function." It's really frustrating

const fileSystem = require('fs'); fileSystem.readFile('analogData.txt', 'utf8', (error, content) => { if (error){ console.log(error); } else console.log(content); }); I am attempting to retrieve data f ...