How to tell webpack dev server to serve index.html

2020-01-27 12:14发布

问题:

React router allows react apps to handle /arbitrary/route. In order this to work, I need my server to send the React app on any matched route.

But webpack dev server doesn't handle arbitrary end points.

There is a solution here using additional express server. How to allow for webpack-dev-server to allow entry points from react-router

But I don't want to fire up another express server to allow route matching. I just want to tell webpack dev server to match any url and send me my react app. please.

回答1:

I found the easiest solution to include a small config:

  devServer: {
    port: 3000,
    historyApiFallback: {
      index: 'index.html'
    }
  }

I found this by visiting: PUSHSTATE WITH WEBPACK-DEV-SERVER.



回答2:

historyApiFallback option on official documentation for webpack-dev-server explains clearly how you can achieve either by using

historyApiFallback: true

which simply falls back to index.html when the route is not found

or

// output.publicPath: '/foo-app/'
historyApiFallback: {
  index: '/foo-app/'
}


回答3:

Works for me like this

devServer: {
    contentBase: "./src",
    hot: true,
    port: 3000,
    historyApiFallback: true

},

Working on riot app



回答4:

Adding public path to config helps webpack to understand real root (/) even when you are on subroutes, eg. /article/uuid

So modify your webpack config and add following:

output: {
    publicPath: "/"
}

devServer: {
    historyApiFallback: true
}

Without publicPath resources might not be loaded properly, only index.html.

Tested on Webpack 4.6

Larger part of config (just to have better picture):

entry: "./main.js",
output: {
  publicPath: "/",
  path: path.join(__dirname, "public"),
  filename: "bundle-[hash].js"
},
devServer: {
  host: "domain.local",
  https: true,
  port: 123,
  hot: true,
  contentBase: "./public",
  inline: true,
  disableHostCheck: true,
  historyApiFallback: true
}


回答5:

My situation was a little different, since I am using the angular CLI with webpack and the 'eject' option after running the ng eject command. I modified the ejected npm script for 'npm start' in the package.json to pass in the --history-api-fallback flag

"start": "webpack-dev-server --port=4200 --history-api-fallback"

"scripts": {
"ng": "ng",
"start": "webpack-dev-server --port=4200 --history-api-fallback",
"build": "webpack",
"test": "karma start ./karma.conf.js",
"lint": "ng lint",
"e2e": "protractor ./protractor.conf.js",
"prepree2e": "npm start",
"pree2e": "webdriver-manager update --standalone false --gecko false --quiet",
"startold": "webpack-dev-server --inline --progress --port 8080",
"testold": "karma start",
"buildold": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail"},


回答6:

If you choose to use webpack-dev-server, you should not use it to serve your entire React app. You should use it to serve your bundle.js file as well as the static dependencies. In this case, you would have to start 2 servers, one for the Node.js entry points, that are actually going to process routes and serve the HTML, and another one for the bundle and static resources.

If you really want a single server, you have to stop using the webpack-dev-server and start using the webpack-dev-middleware within your app-server. It will process bundles "on the fly" (I think it supports caching and hot module replacements) and make sure your calls to bundle.js are always up to date.



回答7:

You can enable historyApiFallback to serve the index.html instead of an 404 error when no other resource has been found at this location.

let devServer = new WebpackDevServer(compiler, {
    historyApiFallback: true,
});

If you want to serve different files for different URIs, you can add basic rewriting rules to this option. The index.html will still be served for other paths.

let devServer = new WebpackDevServer(compiler, {
    historyApiFallback: {
        rewrites: [
            { from: /^\/page1/, to: '/page1.html' },
            { from: /^\/page2/, to: '/page2.html' },
            { from: /^\/page3/, to: '/page3.html' },
        ]
    },
});


回答8:

I know this question is for webpack-dev-server, but for anyone who uses webpack-serve 2.0. with webpack 4.16.5; webpack-serve allows add-ons.You'll need to create serve.config.js:

const serve = require('webpack-serve');
const argv = {};
const config = require('./webpack.config.js');

const history = require('connect-history-api-fallback');
const convert = require('koa-connect');

serve(argv, { config }).then((result) => {
  server.on('listening', ({ server, options }) => {
      options.add: (app, middleware, options) => {

          // HistoryApiFallback
          const historyOptions = {
              // ... configure options
          };

          app.use(convert(history(historyOptions)));
      }
  });
});

Reference

You will need to change the dev script from webpack-serve to node serve.config.js.



回答9:

For me I had dots "." in my path e.g. /orgs.csv so I had to put this in my webpack confg.

devServer: {
  historyApiFallback: {
    disableDotRule: true,
  },
},