webpack-dev-middleware icon indicating copy to clipboard operation
webpack-dev-middleware copied to clipboard

[HMR] Update check failed: SyntaxError: Unexpected token <

Open colinmeinke opened this issue 10 years ago • 21 comments

I'm having an issue with hot module reloading on this repo.

I receive the following error:

[HMR] Update check failed: SyntaxError: Unexpected token <
  at Object.parse (native)
  at XMLHttpRequest.request.onreadystatechange (http://localhost:3000/js/client.js:44:33)

The error comes from within hotDownloadManifest. The request.responseText is HTML, rather than the usual json. This gets passed into JSON.parse which throws. I cannot work out why responseText is HTML.

This repo has a fair amount of CSS split into different files. If I remove a few on the CSS imports it works (most of the time), so my best guess is that it's something to do with a file limit. Could this be the case?

colinmeinke avatar Feb 19 '16 23:02 colinmeinke

This also seems to be a bit random. Sometimes I get the error, sometimes it works as expected. It also seems to happen more often if my initial change is in particular files, especially an imported css file. However, these files do hot reload if my initial change does not cause an error.

colinmeinke avatar Feb 21 '16 20:02 colinmeinke

I'm trying to narrow this down...

This seems to be what is happening when HRM does not work:

  • I make a change to a file
  • Middleware now in invalid state
  • Webpack building...
  • Middleware now in valid state
  • Webpack built c992ed5df30aca44ca5f in 286ms – outputs afe0aa5b3b81aa3836b9.hot-update.json
  • Middleware gets file name from URL – ed251a56a7efd3da32eb.hot-update.json – note how this is different to the file Webpack output
  • Middleware checks file exists – it doesn't
  • Middleware now in invalid state
  • Webpack building...
  • Middleware now in valid state
  • Webpack built bae26c91987acfa361cc in 239ms – afe0aa5b3b81aa3836b9.hot-update.json remains as nothing changed
  • Middleware now assumes ed251a56a7efd3da32eb.hot-update.json file exists and calls fs.statSync on it – it throws
  • Middleware calls next
  • I serve a 404 page for the ed251a56a7efd3da32eb.hot-update.json request
  • webpack passes this HTML response to JSON.parse – HMR dies

When HRM does work the exact process as above takes place, but middleware receives the correct hash for the hot-update.json file, and therefore finds it, handles it and sends a response.

As I said before, it seems to be a bit random as to when it does and does not work. What could be the possible reasons that the middleware receives the incorrect hash?

colinmeinke avatar Feb 21 '16 22:02 colinmeinke

I'm encountering pretty much the same problem. Has anyone managed to find a solution?

andy-mcdonald avatar Jul 16 '16 04:07 andy-mcdonald

I have an issue like this and fixed with: publicPath: 'http://localhost:5000/static'

Webpack don't find the right place to find manifest, or it arrives wrong... But worked!

rodrigonehring avatar Jul 29 '16 12:07 rodrigonehring

@colinmeinke how did you get it working? can I am having the same problem and stuck with it.

savinash47 avatar Aug 16 '16 04:08 savinash47

publicPath can be just '/' it worked for me.

  output: {
    path:       path.join(__dirname, 'public'),
    filename:   './js/webpack/[name].js',
    publicPath: '/',
  },

zirho avatar Aug 28 '16 15:08 zirho

Closing, because the documentation also makes clear that output.publicPath should be set for HMR to work.

SpaceK33z avatar Sep 08 '16 10:09 SpaceK33z

@SpaceK33z it is https://github.com/colinmeinke/colinmeinke/blob/master/webpack/dev/client.babel.js#L52

colinmeinke avatar Sep 08 '16 11:09 colinmeinke

@colinmeinke, you need to use a full URL for HRM:

To teach webpack to make requests (for chunk loading or HMR) to the webpack-dev-server you need to provide a full URL in the output.publicPath option.

source

SpaceK33z avatar Sep 08 '16 12:09 SpaceK33z

Full URL seems unnecessary; a valid URL that starts with / works for me. Notes:

  1. Using a relative URL is wrong.
  2. webpack-hot-middleware doesn't override publicPath in Webpack config - set both to the same correct path as in https://github.com/gaearon/react-transform-boilerplate

stepanh avatar Sep 09 '16 02:09 stepanh

output: { publicPath: '...', // combined with ‘publicPath’ },

ZengTianShengZ avatar Mar 23 '17 15:03 ZengTianShengZ

I'm stuck on the same issue but nothing from above could fix it. Any solutions?

scazzy avatar Jun 01 '17 07:06 scazzy

in you server.js

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


const app = express();
const compiler = webpack(config);
const devMiddleware = webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath, // <------- this  line!
    stats: {colors: true}
})

phdog avatar Jun 02 '17 07:06 phdog

FYI for anyone having issues with this in combination with the vue-cli templates.. I ended up having to add a resolve alias to the webpack configuration to get everything working reliably:

resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias:      {
            'vue$':              'vue/dist/vue.esm.js',
            'socket.io-client$': 'socket.io-client/dist/socket.io.js',
            '@':                 resolve('src')
        }
    },

AYapejian avatar Jan 19 '18 05:01 AYapejian

I am getting this error when I am using webpack 4 with browser-sync even though my publicPath is setup, I am getting this weard hot update on each page reload that simply contains html representation of the page openned.

Here is my config

require('dotenv').config()
var browserSync = require('browser-sync').create()
var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
/**
 * Require ./webpack.config.js and make a bundler from it
 */
var webpackConfig = require('./webpack.config.dev.js')
var bundler = webpack(webpackConfig)

browserSync.init(
{
  proxy:  {
    target: process.env.APP_URL,
    ws: true,
  },
  cors: true,
  https: false,
  port: 3000,
  open: 'external',
  online: false,
  middleware: [
    webpackDevMiddleware(bundler,
    {
      publicPath: webpackConfig.output.publicPath,
      stats:
      {
        warnings: false,
        chunks: false,
        colors: true,
        chunkModules: false,
      },
    }),
    webpackHotMiddleware(bundler),
  ],
  files: ['app/', 'database/', 'migrations/'],
})

This is my webpack config

const webpack = require('webpack')
const rules = require('./webpack-partials/rules')
const alias = require('./webpack-partials/alias')
const utils = require('./webpack-partials/utils')

module.exports = {
  entry: {
    main: [
      'babel-polyfill',
      'webpack/hot/dev-server',
      // ?reload=true enables full page reload on hmr failure
      'webpack-hot-middleware/client?reload=true&noInfo=true',
      'app',
    ],
  },
  mode: 'development',
  context: utils.resolve('resources/assets/js'),
  output: {
    path: utils.resolve('public/js'),
    filename: '[name].js',
    chunkFilename: '[chunkhash].[id].js',
    publicPath: '/js/',
    pathinfo: true,
  },
  devtool: '#eval-source-map',
  module: {
    rules: rules,
  },
  resolve: {
    extensions: ['.js', '.jsx', '.tsx', '.ts', '.vue', '.svg'],
    modules: [
      utils.resolve('resources/assets/js'),
      utils.resolve('resources/assets/js/lib'),
      utils.resolve('node_modules'),
    ],
    alias: alias,
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"',
      },
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
}

Was working fine with webpack 3...

asolopovas avatar Mar 01 '18 13:03 asolopovas

I had to delete my bundled file after everything else and then rerun the build, if anyone is still hitting issues.

sunlee-newyork avatar Mar 29 '18 14:03 sunlee-newyork

For issue theme's this solution is worked for me. In your server.js file:

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.resolve('./dist/public')));
}

I think cause middleware+hot-middleware works like webpack-dev-server and it does not need any additional static files. Also I deleted HtmlWebpackPlugin from webpack.client.config cause server side rendering - gives me initial html markup.

asparkam avatar Apr 06 '18 07:04 asparkam

I ran into this issue and wrestled with (and beat!) it today -- this is the top Google result for the error message in the subject line, so I thought I might shed some additional light on this for those that happen to land here.

The error message is happening because of this code that webpack injects in your client bundle:

request.onreadystatechange = function() {
  if (request.readyState !== 4) return;
  if (request.status === 0) {
    // timeout
    reject(
      new Error("Manifest request to " + requestPath + " timed out.")
    );
  } else if (request.status === 404) {
    // no update available
    resolve();
  } else if (request.status !== 200 && request.status !== 304) {
    // other failure
    reject(new Error("Manifest request to " + requestPath + " failed."));
  } else {
    // success
    try {
      var update = JSON.parse(request.responseText);
    } catch (e) {
      reject(e);
      return;
    }
    resolve(update);
  }
}

The HMR module is trying to look for an update JSON manifest, and when there's none available, your server should be returning a 404 or 500. What's causing this error is that your server is returning a 200/304 and, perhaps, some default html (hence the 'unexpected token <') when it's expecting JSON.

For me at least, this was caused by not handling 404 errors properly in my Express app -- I was testing HMR before I was ready to :)

So make sure you're returning proper error codes for asset files in your publicPath and you should be good!

noahlh avatar Jan 28 '19 05:01 noahlh

Finally I found the solution for this error

just change, app.get('*', (req, res) => { res.sendFile(indexHtml); });

To

app.get('/', (req, res) => { res.sendFile(indexHtml); });

It works to me

csbblabsystemvsb123 avatar Dec 10 '19 09:12 csbblabsystemvsb123

I opened my local url with: http://localhost/ instead of http://localhost:3000/

This caused the error.

migliori avatar Aug 15 '20 16:08 migliori