Skip to content

Uncaught SyntaxError: Unexpected token < #205

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

Closed
hackingbeauty opened this issue Jul 14, 2017 · 22 comments
Closed

Uncaught SyntaxError: Unexpected token < #205

hackingbeauty opened this issue Jul 14, 2017 · 22 comments

Comments

@hackingbeauty
Copy link

  • Operating System: Mac OS
  • Node Version: 6.2.0
  • NPM Version: 4.4.4
  • webpack version: 3
  • webpack-dev-middleware Version: 1.11.0
  • [X ] This is a bug

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

What's the stack trace?

@hackingbeauty
Copy link
Author

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

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

@shellscape
Copy link
Contributor

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

@hackingbeauty
Copy link
Author

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

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

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

petetnt commented Jul 17, 2017

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

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

DeekshaPandit commented Mar 21, 2018

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

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

@alexander-lebed
Copy link

Make sure you use the right port

@spmsupun
Copy link

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

@ZaynJarvis
Copy link

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

qkreltms commented Jan 19, 2019

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

@sc410wbt
Copy link

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

kopax commented Apr 29, 2020

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

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

@kopax
Copy link

kopax commented May 1, 2020

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

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

olyop commented Jul 22, 2020

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

@mgdeveloper79
Copy link

mgdeveloper79 commented Aug 4, 2021

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

{
"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"
}

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

No branches or pull requests