1

I can't seem to figure out how to get hot module replacement to work. Every time I make a change to my html file or my CSS files the webpack always does a refresh to show the changes.

webpack.config.js

const path = require('path')

const postCSSPlugins = [
    require('postcss-simple-vars'),
    require('postcss-nested'),
    require('autoprefixer'),
    require('postcss-import')
]

module.exports = {
    entry: './app/assets/scripts/App.js',
    output: {
        filename: 'bundled.js',
        path: path.resolve(__dirname, 'app')
    },
    devServer: {
        watchFiles: ('./app/**/*.html'),
        static: path.join(__dirname, 'app'),
        hot: true,
        port: 3000,
        host: '0.0.0.0'
    },
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: ['style-loader','css-loader', {loader: 'postcss-loader', options: {postcssOptions: {plugins: postCSSPlugins}}}]
            }
        ]
    }
}

package.json

  "scripts": {
    "dev": "webpack serve --hot",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "autoprefixer": "^10.4.2",
    "css-loader": "^6.6.0",
    "postcss-import": "^14.0.2",
    "postcss-loader": "^6.2.1",
    "postcss-nested": "^5.0.6",
    "postcss-simple-vars": "^6.0.3",
    "style-loader": "^3.3.1",
    "webpack": "^5.69.1",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.7.4"
  }

App.js

import '../styles/styles.css'

if(module.hot) {
    module.hot.accept(function() {
        console.log("Accepting the updated modules...")
    })
}

What I've tried..

  • I've tried using the hotOnly option but its been removed
  • I've tried add an option tag in the CLI in my package.json file

Nothing seems to be working. Anytime I make a change the whole page refreshes.

Nick
  • 624
  • 8
  • 24
  • Could you please provide what Webpack logs to browser's consle? Do not forget to check "preserve log" – Limbo May 09 '22 at 19:57
  • Faced simillar issue, but with `style-loader`. The problem was that folder specified in `devServer.static` contained my application, so Webpack thought that whole source code is static and refreshed the page on each update. – Limbo May 09 '22 at 21:31

1 Answers1

0

To figure out how Hot Module Reload works and is set up you may take a look at my post here. Remove --host 0.0.0.0 if you don't use it with Docker.

Maksym Dudyk
  • 1,082
  • 14
  • 16