Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
colinmeinke opened this issue Feb 19, 2016 · 21 comments
Closed

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

colinmeinke opened this issue Feb 19, 2016 · 21 comments

Comments

@colinmeinke
Copy link

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
Copy link
Author

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
Copy link
Author

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?

@andy-mcdonald
Copy link

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

@rodrigonehring
Copy link

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!

@savinash47
Copy link

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

@zirho
Copy link

zirho commented Aug 28, 2016

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

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

@SpaceK33z
Copy link
Member

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

@SpaceK33z
Copy link
Member

@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

@stepanh
Copy link

stepanh commented Sep 9, 2016

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

@ZengTianShengZ
Copy link

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

@scazzy
Copy link

scazzy commented Jun 1, 2017

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

@phdog
Copy link

phdog commented Jun 2, 2017

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}
})

@AYapejian
Copy link

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')
        }
    },

@asolopovas
Copy link

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...

@sunlee-newyork
Copy link

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

@asparkam
Copy link

asparkam commented Apr 6, 2018

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.

@noahlh
Copy link

noahlh commented Jan 28, 2019

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!

@csbblabsystemvsb123
Copy link

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

@migliori
Copy link

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

This caused the error.

@Rowleen
Copy link

Rowleen commented Nov 30, 2020

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

This worked for me too. Thanks so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests