webpack / webpack-dev-middleware

A development middleware for webpack
MIT License
2.5k stars 376 forks source link

Uncaught SyntaxError: Unexpected token < #205

Closed hackingbeauty closed 7 years ago

hackingbeauty commented 7 years ago

Hello, I'm using a package called "connect-history-api-fallback" in order to allow for html5 pushState with webpack-dev-middleware. However, I noticed that with multiple parts in a route (/user/12345), I'm getting an "Unexpected token <" error. There is no error when the route has only one part (/user).

Here is a public gist for my server set up: https://gist.github.com/hackingbeauty/3654f5dae04abf9aa480d2823cc5e184

Is there any way I can patch this?

shellscape commented 7 years ago

What's the stack trace?

hackingbeauty commented 7 years ago

There is none.

I just get the error: "bundle.js:1 Uncaught SyntaxError: Unexpected token <" located on line 1 of my JS file titled "bundle.js".

If I click on bundle.js, it brings me to the main HTML page of the app and points to the first line which is "<!DOCTYPE html>".

Is the middleware somehow trying to parse the main index.html page?

shellscape commented 7 years ago

I'm not familiar with a circumstance in which it would. You may have stumbled across an urksome edge case.

hackingbeauty commented 7 years ago

Is it probable that the issue is coming from the "connect-history-api-fallback" package? I need to get webpack-dev-middleware to work with html5 pushState.

Or should I look at using webpack-dev-server instead? Thank you for responding!

shellscape commented 7 years ago

Well webpack-dev-server uses this module under the hood, so you'd likely run into the same problem. Any way to remove the history fallback to weed that out as the possible culprit?

hackingbeauty commented 7 years ago

When I remove the history fallback, the error does indeed go away. However, I can no longer use html5 push state, which means my URLs then need to have a hashbang (/#/user/1234).

Again, this problem only occurs for routes with multiple parts (/users/1234).

petetnt commented 7 years ago

Hey @hackingbeauty,

check the headers on the call that errors out; the Unexpected token < error is due to wrong application-type (for example text/html for a JS file, or application/javascript for HTML file).

This option looks promising too, maybe try setting it to htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] for example.

hackingbeauty commented 7 years ago

Hey awesome peeps, I fixed the problem. It was a Webpack config issue that only affected routes with multiple "/" in the URL. I tweaked publicPath in Webpack to use an absolute vs relative path.

  entry: [
    'webpack-hot-middleware/client',
    './src/index',
  ],
  output: {
    publicPath: '/', // if you don't put the "/" here, you get this error:
  },                 // "bundle.js:1 Uncaught SyntaxError: Unexpected token <"

Thank you for taking the time to respond to my issue.

DeekshaPandit commented 6 years ago

I am running into same issue.

and my webpack files are like this.

var path = require('path')
var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src/entry-client.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },
      {
        test: /\.scss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader'
        ],
      },
      {
        test: /\.sass$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader?indentedSyntax'
        ],
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': [
              'vue-style-loader',
              'css-loader',
              'sass-loader'
            ],
            'sass': [
              'vue-style-loader',
              'css-loader',
              'sass-loader?indentedSyntax'
            ]
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    }),
     new HtmlWebpackPlugin(
       {
        filename: 'index.html',
        template: 'index.html'
       }
     )
  ])
}

and

var path = require('path')
var webpack = require('webpack')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.config')

var webpackConfig = merge(baseWebpackConfig, {
    target: 'node',
    entry: {
        app: './src/entry-server.js'
    },
    devtool: false,
    output: {
        path: path.resolve(__dirname, './dist'),
        publicPath:'/',
        filename: 'server.bundle.js',
        libraryTarget: 'commonjs2'
    },
    externals: Object.keys(require('./package.json').dependencies),
    plugins: [
        new webpack.DefinePlugin({
            'process.env': 'production'
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    ]
})
module.exports = webpackConfig

Can anyone please check it for me?

evenstensberg commented 6 years ago

@DeekshaPandit Did you try the previous solution? Try posting to SO as well

alexander-lebed commented 6 years ago

Make sure you use the right port

spmsupun commented 6 years ago

You have two watch command running in separate window, if it's not visible try restarting the node (or pc)

ZaynJarvis commented 5 years ago

Try to add this <base href="/" /> to <head> of index.html. Solution got from here This is because of HTML rendering. <base> is to set something like a root node.

qkreltms commented 5 years ago

@DeekshaPandit try publicPath: '/dist/' to publicPath: '/' it fixed my issue.

sc410wbt commented 4 years ago

Try to add this <base href="/" /> to <head> of index.html. Solution got from here This is because of HTML rendering. <base> is to set something like a root node.

Tried the publicPath fix to no avail, but this one did the trick. Thanks!

kopax commented 4 years ago

I have the same issue within Docker after releasing a new version. I am not sure but I believe this is due to a chunk not being available anymore and the old version get the default * route which is the index.html. any idea how I can solve this ? I believe keeping old chunk across docker release new version is a challenges

alexander-akait commented 4 years ago

Most often this happens when you got 404 error and you server return html context

kopax commented 4 years ago

yes that is exactly what I said. But how can I prevent the .js file to return the .html within express ?

Keeping old chunk for old versions is a challenge, I should reload the application somehow when this happen, I am not sure where to add this line of code, perhaps the server can send a window.reload when the js file is not found.

santaclauze commented 4 years ago

I continue encountering a similar issue as well. It happens randomly where a specific page will just appear blank and log that exact error. It seems to be inconsistent.

I implemented a retry for failed chunks -> https://github.com/mattlewis92/webpack-retry-chunk-load-plugin. This has solved some issues related to slow connections but errors still show up intermittently.

olyop commented 4 years ago

For me I solved it by adding .js to the resolve.extensions array. Not sure about the source of the problem.

mgdeveloper79 commented 3 years ago

Fix: In Webpack version 5.46.0. Node 14.x. I am posting this in a hope help others incase if they reach this far and still have not found a fix. So along with many other issues, one possibility is if you are using html-webpack-plugin, you may find this useful. We are using the html-webpack-plugin and the publicPath attribute needed to be explicitly set in the properties, which was not the case with the former webpack < 5 versions of the plugin, where it was supposedly inheriting the property from the output/devServer. After adding the property to the plugin, it worked in webpack 5 with the latest html-webpack-plugin.

Here is the relevant config.

module.exports = {
  mode: 'development',
entry: ['@babel/polyfill', './config/polyfills', './src/index.js'],
  output: {
    hotUpdateMainFilename: '[id].hot-update.[fullhash].json',
    hotUpdateChunkFilename: '[id].hot-update.[fullhash].js',
    path: resolve(__dirname, '..', 'dist'),
    filename: '[name].[fullhash].js',
  },
  optimization: {
    moduleIds: 'named',
  },
  devtool: 'eval-cheap-module-source-map',
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      hash: true,
      publicPath: '/yourPath/',
      template: resolve(__dirname, '..', 'src', 'index.html'),
      alwaysWriteToDisk: true,
    }),
    new HtmlWebpackHarddiskPlugin({
      outputPath: resolve(__dirname, '..', 'dist'),
    }),
  ],
};
kuldeep0302 commented 8 months ago

{ "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": "/", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" }

<!DOCTYPE html>

Nural Service Managment Repair

not resolved