webpack-dev-server: Webpack dev server is not serving the latest compiled code

bug

What is the current behavior? Webpack-dev-server is not updating the browser with latest built code

Webpack configuration

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const ngtools = require('@ngtools/webpack');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');

module.exports = function (env) {
    const config = {
        entry: {
            polyfill: './src/polyfills.ts',
            vendor: './src/vendors.ts',
            main: './src/main.aot.ts'
        },
        resolve: {
            extensions: [".js", ".json", ".ts"]
        },
        output: {
            filename: '[name].js',
            path: path.resolve('dist')
        },
        module: {
            rules: [
                {
                    test: /\.ts?$/,
                    use: '@ngtools/webpack'
                },
                {
                    test: /\.css$/,
                    //exclude:'node_modules',
                    include: path.resolve(process.cwd(), 'src', 'app'),
                    use: ['to-string-loader', 'css-loader']
                }
            ]
        },
        plugins: [
            new HtmlWebpackPlugin({
                template: "./src/index.html"
            }),
            new ExtractTextPlugin("styles.css"),
            new webpack.ContextReplacementPlugin(
                /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
                __dirname
            ),
            new webpack.HotModuleReplacementPlugin()
        ],
        devtool: "source-map",
        target: "web",
        stats: "errors-only",
        devServer: {
            contentBase: path.join(__dirname, "dist"),
            compress: true,
            port: 8080,
            clientLogLevel: "none",
            historyApiFallback: true,
            watchContentBase: true
        }
    };
    return config;
};

for serve the application through npm script "start": "webpack-dev-server --progress --color --env.development --config tools/webpack.js"

What is the expected behavior? It should always serve the latest compiled code. If this is a feature request, what is motivation or use case for changing the behavior?

Please mention your webpack and Operating System version.

“webpack”: “2.2.1”, “webpack-dev-server”: “2.4.2”,

Every time i change a file i can see in console that webpack is compiling and browser is refreshing but output in browser is same as last compiled code

UPDATE

this is re-producible only when you use @ngtools/webpack plugin otherwise using ts-loader works just fine.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 38
  • Comments: 72 (3 by maintainers)

Most upvoted comments

I don’t understand why this issue is closed. It’s not working even with a basic configuration. The only workaround is to use webpack --watch.

Folks, please don’t follow up with “same” or “me too” comments unless you have additional info, aside from your environment/os, to add to the original issue. Please use the reaction button to add a 👍 to the original post.

That said, we’d happily review a pull request for this issue.

+1 for this issue, I’m on a mac, don’t think it’s a windows specific issue.

I spilled a cup of coffee on my keyboard and now it started working

So, I read the docs and it turns out that I needed to add same publicPath in output and devServer properties like so,

 output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'js'),
    publicPath: path.resolve(__dirname, '/js/')
  },
  devServer: {
    contentBase: path.resolve(__dirname, './'),
    publicPath: path.resolve(__dirname, '/js/'),
  },

removing devServer option hot: true fixed it for me.

FWIW, I was having a similar symptom (browser was always getting a stale version of the compiled files), which brought me to this issue, BUT in my case the problem was deeper: webpack wasn’t actually picking up changes and recompiling.

I’m using a Xubuntu 16.04 guest in a Windows 8.1 Virtualbox host, using Node 8.6.0, and webpack --watch itself wasn’t being notified of changes in the source files. I added the polling option to my webpack.config.js and it started working (even hot reloading):

module.exports = {
  ...
  watchOptions: {
    poll: true
  }
}

I knew there were problems with watches on shared Virtualbox folders, but this particular VM doesn’t have any shared folders – all files are inside the VM.

I’m getting the same behavior. Initial compilation succeeds and all bundles load in the browser. Any subsequent change is (ostensibly) compiled by Webpack but is not available in the browser.

macOS 10.12.5 Webpack 3.4.1 webpack-dev-server 2.6.1 ts-loader 2.3.2 typescript 2.4.2

webpack: Compiled successfully.
webpack: Compiling...
Hash: 4c58a816563875a772dd
Version: webpack 3.4.1
Time: 1830ms
                               Asset      Size  Chunks                    Chunk Names
                       app.bundle.js    568 kB       0  [emitted]  [big]  app
                    vendor.bundle.js   5.37 MB       3  [emitted]  [big]  vendor
0.9bb86568f99493e5e6b1.hot-update.js   19.3 kB       0  [emitted]         app
9bb86568f99493e5e6b1.hot-update.json  43 bytes          [emitted]         
 [209] (webpack)/hot nonrecursive ^\.\/log$ 170 bytes {3} [built]
 [246] ./src/ts/app/.../foo.ts 7 kB {0} [built]
    + 300 hidden modules
webpack: Compiled successfully.
webpack: Compiling...
Hash: f7a6e2addadcc8d90ea0
Version: webpack 3.4.1
Time: 1618ms
                               Asset      Size  Chunks                    Chunk Names
                       app.bundle.js    568 kB       0  [emitted]  [big]  app
                    vendor.bundle.js   5.37 MB       3  [emitted]  [big]  vendor
0.4c58a816563875a772dd.hot-update.js   19.3 kB       0  [emitted]         app
4c58a816563875a772dd.hot-update.json  43 bytes          [emitted]         
 [209] (webpack)/hot nonrecursive ^\.\/log$ 170 bytes {3} [built]
 [246] ./src/ts/app/.../foo.ts 7 kB {0} [built]
    + 300 hidden modules
webpack: Compiled successfully.

Restarting the computer fixed it for me 😕

Tested with simple app and everything works (node: v8.9.4; webpack: 3.11.0; webpack-dev-server: 2.11.1)

appRoot
├── node_modules
├── public
│  ├── index.html
│  ├── scripts
│  │   └── bundle.js
│  └── styles
│       └── main.css
├── src
│   └── index.js
...

index.html

...
    <script src="scripts/bundle.js"></script>
  </body>
</html>

webpack.config.js

const path = require('path')

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'public/scripts')
  },
  devtool: 'source-map',
  devServer: {
    contentBase: path.resolve(__dirname, 'public'),
    publicPath: '/scripts/',
    host: '127.0.0.1',
    port: 8080,
    open: true
  }
}

Note: it’s important that <script src="scripts/bundle.js"> points to the same path as devServer.publicPath (ie. http://127.0.0.1:8080/scripts/bundle.js)

Adding this to the webpack.config.js file did the trick for me:

devServer: {publicPath: '/public', port: 8080},

same problem

Still getting this issue, workarounds don’t work.

As I have mentioned here. I was getting bundle file from /dist builded earlier, not the one served from memory.

This feature If you're having trouble, navigating to the /webpack-dev-server route will show where files are served. For example, http://localhost:9000/webpack-dev-server. (src) saves me, I was able to understand how files are served, then I have changed it by publicPath. 🎉

My problem was in my multiple webpack config environment, so files were served in named contexts. Like: http://localhost:9000/webpackConfig1/yourFiles http://localhost:9000/webpackConfig2/yourFiles … etc

if the webpack not serving code changes so in webpack.congif.js write :

module.exports = { //… devServer: { watchOptions: { poll: true } } };

for further information see this link: https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

Still stuck on this issue 😦

folks, we’ve got a few workarounds listed in this issue for various cases that produce the same result. we’ll reopen if someone can nail down a specific culprit within webpack-dev-server to discuss, and as always we’d happily accept a PR for review. given the age of this issue, the multiple edges that this can be experienced on, and the multiple workarounds, we’re going to close this one.

Nope. webpack-dev-server won’t recompile or reload for me either, tried all the above fixes.

Same problem here for now I use:

    "watch": "webpack --progress --watch",
    "start": "concurrently -k -p \"[{name}]\" -n \"Webpack,HTTP-Server\" -c \"cyan.bold,green.bold\"  \"npm run watch\" \"npm run serve\" ",
    "serve": "http-server ./dist -p 8081 -o"

The only thing missing it auto-reload

I had the same issue, the culprit was webpack-chunk-hash. Removing it from my webpack config solved the problem.


My Packages:

"devDependencies": {
    "@types/facebook-js-sdk": "^2.8.3",
    "@types/node": "^8.0.25",
    "angular2-template-loader": "^0.6.2",
    "autoprefixer": "^7.1.2",
    "awesome-typescript-loader": "^3.0.4-rc.2",
    "codelyzer": "^3.1.2",
    "css-loader": "^0.28.5",
    "extract-text-webpack-plugin": "^3.0.0",
    "file-loader": "^0.11.2",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.28.0",
    "image-webpack-loader": "^3.2.0",
    "inline-manifest-webpack-plugin": "^3.0.1",
    "node-sass": "^4.5.0",
    "postcss-flexbugs-fixes": "^3.2.0",
    "postcss-load-config": "^1.2.0",
    "postcss-loader": "^2.0.6",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.5.4",
    "sass-loader": "^6.0.0",
    "script-ext-html-webpack-plugin": "^1.8.5",
    "style-loader": "^0.18.2",
    "tslint": "^5.7.0",
    "tslint-loader": "^3.4.2",
    "typescript": "^2.5.1",
    "webpack": "^3.5.5",
    "webpack-dev-server": "^2.7.1",
    "webpack-merge": "^4.1.0"
  },
  "dependencies": {
    "@angular/common": "^4.3.6",
    "@angular/compiler": "^4.3.6",
    "@angular/core": "^4.3.6",
    "@angular/forms": "^4.3.6",
    "@angular/http": "^4.3.6",
    "@angular/platform-browser": "^4.3.6",
    "@angular/platform-browser-dynamic": "^4.3.6",
    "@angular/router": "^4.3.6",
    "core-js": "^2.5.0",
    "rxjs": "^5.4.3",
    "zone.js": "^0.8.17"
  }

Webpack config:

module.exports = {
    entry: {
        'polyfills': './src/polyfills.ts',
        'vendor': './src/vendor.ts',
        'app': './src/main.ts'
    },
    output: {
        path: helpers.root('dist'),
        // publicPath: '/',
        filename: '[name].[chunkhash].js',
        chunkFilename: '[id].[chunkhash].chunk.js'
    },
    module: {
        rules: [{
            test: /\.ts$/,
            loaders: [{
                loader: 'awesome-typescript-loader',
                options: {
                    configFileName: helpers.root('src', 'tsconfig.json')
                }
            },
                'angular2-template-loader'
            ]
        }, {
            test: /\.html$/,
            loader: 'html-loader',
            query: {
                ignoreCustomFragments: [/\{\{.*?}}/],
                root: helpers.root('src'),
                attrs: ['img:src', 'img:ng-src']
            }
        }, {
            test: /\.(png|jpe?g|gif|svg)$/i,
            loaders: [
                'file-loader?hash=sha512&digest=hex&name=images/[name].[hash].[ext]',
                'image-webpack-loader'
            ]
        }, {
            test: /\.(eot|otf|ttf|woff|woff2)$/i,
            loader: 'file-loader?hash=sha512&digest=hex&name=fonts/[name].[hash].[ext]'
        }, {
            test: /\.scss$/,
            exclude: [helpers.root('src', 'app')],
            loader: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: [
                    {
                        loader: 'css-loader',
                        options: {
                            sourceMap: true,
                            importLoaders: true
                        }
                    }, {
                        loader: 'postcss-loader',
                        options: {
                            sourceMap: true
                        }
                    }, {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true
                        }
                    }
                ]
            })
        },
            {
                test: /\.scss$/,
                include: [helpers.root('src', 'app')],
                loaders: [
                    {
                        loader: 'raw-loader'
                    }, {
                        loader: 'postcss-loader',
                        options: {
                            sourceMap: true
                        }
                    }, {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true
                        }
                    }
                ]
            }
        ]
    },

    plugins: [
        // Workaround for angular/angular#11580
        new webpack.ContextReplacementPlugin(
            /angular(\\|\/)core(\\|\/)@angular/, // The (\\|\/) piece accounts for path separators in *nix and Windows
            helpers.root('./src'), // location of your src
            {} // your Angular Async Route paths relative to this root directory
        ),
        new webpack.optimize.CommonsChunkPlugin({
            name: ['vendor', 'polyfills', 'manifest'],
            minChunks: Infinity
        }),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.HashedModuleIdsPlugin(),
        //new WebpackChunkHash(), // <---------- **Removed this**.
        new InlineManifestWebpackPlugin({
            name: 'webpackManifest'
        }),
        new HtmlWebpackPlugin({
            template: helpers.root('src', 'index.ejs'),
            filename: helpers.root('dist', 'index.html'),
            minify: {
                removeComments: true
            }
        }),
        new ScriptExtHtmlWebpackPlugin({
            defer: [/app/, /vendor/, /polyfills/],
            defaultAttribute: 'async'
        }),
        new ExtractTextPlugin({
            filename: '[name].[contentHash].css',
            allChunks: true
        })
    ],
    resolve: {
        extensions: ['.ts', '.js']
    },
    devServer: {
        historyApiFallback: true,
        stats: 'minimal',
        compress: true,
        inline: true,
        port: 8080
    }
};

like @albertian mentioned and has shown in the example publicPath for output and devServer needs to be same.

webpack-dev-server doesn’t serve the actual generated bundle from file system. Rather it’ll watch your source files, and recompile the bundle whenever they are changed. This modified bundle is served directly from memory.

Why webpack-dev-server Live-Reload Is Not Working

Webpack — Understanding the ‘publicPath’ mystery

These two articles explains in deep about live reloading and publicPath.

Not working for me… so i just switched to using npm ‘live-server’ and ‘webpack --watch’.

Apparently, the problem was never solved 😭

Hello, had the same issue. Here’s what fixed it for me: I had "webpack-dev-server --config webpack.config.dev.js --content-base ./ --port 1729 --progress --inline" in my package.json, removing the --content-base ./ fixed it, no need to specify the content-base really, it comes out of the box

I’m having kind of the same issue, but mine is it serves latest compiled code at the start, but after some time it reverts back to who knows how old compiled code (can be minutes, can be seconds, even when not changing anything) until you restart the dev server, and the it just repeats.

Windows 10 Webpack 3.4.1 webpack-dev-server: 2.6.1

I have struggled with this for the better part of a day, then I found this help https://medium.com/bcgdv-engineering/when-using-react-js-webpack-dev-server-does-not-bundle-c2d340b0a3e8

@gzoritchak Can’t tell you how grateful I am for your comment.

Removing experimentalWatchApi: true from ts-loader options helped me!

i had the same problem, i tried all of these suggestions, but none of them woks for me. finally, i tried to add a newline at the end of the webpack configuration and it just worked! awesome!

Thanks for pointing these out, @khyamay! It really helped me understand how webpack-dev-server works.

like @albertian mentioned and has shown in the example publicPath for output and devServer needs to be same.

webpack-dev-server doesn’t serve the actual generated bundle from file system. Rather it’ll watch your source files, and recompile the bundle whenever they are changed. This modified bundle is served directly from memory.

Why webpack-dev-server Live-Reload Is Not Working

Webpack — Understanding the ‘publicPath’ mystery

These two articles explains in deep about live reloading and publicPath.

The “Why webpack-dev-server Live-Reload Is Not Working” article is what everyone here should read. This contains most of the answers to the questions here that keep getting repeated.

Having local files in an output dir from webpack-cli will cause problems. Remove them or output them to a different path if you are going to use the dev server.

I’m on ubuntu 18.04 and i fix this issue following Visual Code guidelines.

Hope it will help.

Hi guys. I’m a newbie in Webpack and I got the same problem. But now it works good. Even without bundle.js file my server works correctly. command: node_modules/.bin/webpack-dev-server --config webpack.config.js --hot webpack.config.js

output: {
        path: __dirname + '/js',
        publicPath: '/js',
        filename: 'bundle.js'
    },
    devServer: {
        contentBase:__dirname + '/',
        publicPath: '/js'
    },

Both publicPath are url path, so not need to put your file path here. After my changes my webpage reloades after each file change. I hope it will be helpful so someone.

Just in case this might help someone else, I tried most of the solutions here which did not work for me and wound up just moving my project files from the nested directory they were in onto the desktop, and then webpack dev server worked as expected and the problem was solved. I have no idea why this works, but just wanted to pass the (simple) solution on in case it helps someone else who has tried all of the above to see if just moving the project files will work. (FYI, I’m just running on Windows native environment) Good luck…

I was having a similar issue using webpack-dev-middleware with webpack-hot-middleware. The updated bundle was not served after the initial build (first start) of dev server. The updated bundle was served only after forcing webpack to rebuild, e.g. saving any watched project file, and making a hard refresh in the browser.

The solution I’ve found is to force recompilation in the setup script using devMiddleware.invalidate method.

Currently using this bootstrap script:

const webpack = require('webpack');
const express = require('express');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('../webpack.config')('development');

const compiler = webpack(config);
const app = express();

const devMiddleware = webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath,
  historyApiFallback: true,
  hot: true,
  inline: true,
});

/**
 * This method call instructs a webpack-dev-middleware instance to recompile the bundle
 */
devMiddleware.invalidate();

app.use(webpackHotMiddleware(compiler, { noInfo: false }));
app.use(devMiddleware);


app.get('*', (req, res) => {
  const htmlBuffer = devMiddleware.fileSystem.readFileSync(`${config.output.path}/index.html`)

  res.send(htmlBuffer.toString())
})

app.listen(8181, 'localhost');

This stackoverflow answer may be helpful. https://stackoverflow.com/a/42717524

other workaround is to use webpack --watch but hot reload is not there in that option.

I had the same issue, upgrading packages worked for me 😃

Fix for me : disable all chrome plugins that have similar features to hot reload in my case “LiveReload” & “JetBrains IDE support”.