How to remove the port from URL in Webpack Dev Server hot reload?

Viewed 2605

I'm running my app on localhost port 80 with an alias (I need this for php backend) The frontend is running with VueJs + Webpack + Hot Module Reload on port 3000 using a proxy.

I setup my webpack.config.js and everything is fine, except that I can't figure out how to remove the :3000 from the url.

If I open http://my-alias instead of http://my-alias:3000 Hot Module Reload fails with

[HMR] Update failed: SyntaxError: Unexpected token < in JSON at position 0

Here's an extract of my webpack.config.js:

module.exports = (env, argv) => {
    return {
        mode: env.NODE_ENV,
        watch: false,
        entry: {
            main: './src/main.js'
        },
        output: {
            path: path.resolve(__dirname, 'assets/javascripts'),
            publicPath: '/assets/javascripts/',
            filename: env.NODE_ENV === 'production' ? '[name].min.js' : '[name].js'
        },
        devServer: {
            hot: true,
            open: false,
            publicPath: '/assets/javascripts/',
            contentBase: [path.resolve(__dirname, 'index.php')],
            watchContentBase: true,
            compress: true,
            port: 3000,
            host: 'my-alias',
            historyApiFallback: true,
            proxy: {
                '*': {
                    target: 'http://my-alias',
                    secure: false,
                    changeOrigin: true
                }
            },
            // ... etc
        },

Any idea?

2 Answers

In my case it is a React app with a PHP backend, I didn't use alias, I just add the scripts names in my index.php and defined the root div (this is just for the dev config env).

<?php
// index.php at http://localhost/
?>
  <div id="root"></div>
  <script src="http://localhost:3000/">
  <script src="http://192.168.1.111:3000/static/js/bundle.js">
  <script src="http://192.168.1.111:3000/static/js/vendors~main.chunk.js">
  <script src="http://192.168.1.111:3000/static/js/main.chunk.js">
 //...

Add the CORS middleware in webpack to be able to load the js files from another domain (diffrent port).

const corsMiddleWare = (req, res, next) => {
 res.append('Access-Control-Allow-Origin', ['*']);
 res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
 res.append('Access-Control-Allow-Headers', 'Content-Type');
 next();
}
//...
before(app, server) {
//...
  app.use(corsMiddleWare);
//...

And crossOriginLoading and publicPath in the Webpack output config

 output: {
  /* your config */
  crossOriginLoading: 'anonymous',
  publicPath: 'http://localhost:3000/',
 }

With this config I am able to visit http://localhost, run the React app, and the hot reload works fine, in your case you can follow the same steps or update just the publicPath.

Related