historyApiFallback 在 Webpack 开发服务器中不起作用

historyApiFallback doesn't work in Webpack dev server

我使用 Webpack 开发服务器并且 browserHistory in React Router to manipulate with urls by HTML5 History API. historyapifallback-option 在我的 webpack 配置文件中不起作用。刷新 http://localhost:8080/usershttp://localhost:8080/products 我得到 404.

webpack.config.js

var webpack = require('webpack');
var merge = require('webpack-merge');

const TARGET = process.env.npm_lifecycle_event;

var common = {
    cache: true,
    debug: true,
    entry: './src/script/index.jsx',
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    output: {
        sourceMapFilename: '[file].map'
    },
    module: {
        loaders: [
            {
                test: /\.js[x]?$/,
                loader: 'babel-loader',
                exclude: /(node_modules)/
            }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ]
};

if(TARGET === 'dev' || !TARGET) {
    module.exports = merge(common,{
        devtool: 'eval-source-map',
        devServer: {
            historyApiFallback: true
        },
        output: {
            filename: 'index.js',
            publicPath: 'http://localhost:8090/assets/'
        },
        plugins: [
            new webpack.DefinePlugin({
                'process.env.NODE_ENV': JSON.stringify('dev')
            })
        ]
    });
}

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
        <title>Test</title>
    </head>
    <body>
        <div id="content">
            <!-- this is where the root react component will get rendered -->
        </div>
        <script src="http://localhost:8090/webpack-dev-server.js"></script>
        <script type="text/javascript" src="http://localhost:8090/assets/index.js"></script>
    </body>
</html>

index.jsx

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, useRouterHistory, browserHistory, Link} from 'react-router';

class Home extends Component{
  constructor(props) {
    super(props);
  }

  render() {
      return <div>
          I am home component
          <Link to="/users" activeClassName="active">Users</Link>
          <Link to="/products" activeClassName="active">Products</Link>
        </div>;
  }
}

class Users extends Component{
  constructor(props) {
    super(props);
  }

  render() {
      return <div> I am Users component </div>;
  }
}

class Products extends Component{
  constructor(props) {
    super(props);
  }

  render() {
      return <div> I am Products component </div>;
  }
}

ReactDOM.render(
    <Router history={browserHistory} onUpdate={() => window.scrollTo(0, 0)}>
        <Route path="/" component={Home}/>
        <Route path="/users" component={Users} type="users"/>
        <Route path="/products" component={Products} type="products"/>
    </Router>
    , document.getElementById('content'));

package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.jsx",
  "scripts": {
    "start": "npm run serve | npm run dev",
    "serve": "./node_modules/.bin/http-server -p 8080",
    "dev": "webpack-dev-server -d --progress --colors --port 8090 --history-api-fallback"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "events": "^1.1.0",
    "jquery": "^2.2.3",
    "path": "^0.12.7",
    "react": "^15.0.2",
    "react-dom": "^15.0.2",
    "react-mixin": "^3.0.5",
    "react-router": "^2.4.0"
  },
  "devDependencies": {
    "babel": "^6.5.2",
    "babel-core": "^6.8.0",
    "babel-loader": "^6.2.4",
    "babel-polyfill": "^6.8.0",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babel-register": "^6.8.0",
    "http-server": "^0.9.0",
    "webpack": "^1.13.0",
    "webpack-dev-server": "^1.14.1",
    "webpack-merge": "^0.12.0"
  }
}

我试图在我的配置中更改 devServer,但没有帮助:

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

devServer: {
    historyApiFallback: {
        index: 'index.js',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets/',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets/index.html',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets/index.js',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets/index.js',
    }
},
output: {
    filename: 'index.js',
            publicPath: 'http://localhost:8090/assets/'
},

我今天遇到了同样的问题。 让webpack.config.js中的config:output.publicPath等于devServer.historyApiFallback.index和指出html文件路由。我的webpack-dev-server版本是 1.10.1 并且运行良好。 http://webpack.github.io/docs/webpack-dev-server.html#the-historyapifallback-option不行,必须指出html文件路径。

例如

module.exports = {
    entry: "./src/app/index.js",
    output: {
        path: path.resolve(__dirname, 'build'),
        publicPath: 'build',
        filename: 'bundle-main.js'
    },
    devServer: {
        historyApiFallback:{
            index:'build/index.html'
        },
    },
};

historyApiFallback.index 表示当 url 路径不匹配真实文件时,webpack-dev-server 使用 historyApiFallback.index 中的文件配置在浏览器中显示而不是 404 页面。然后所有关于你的路线改变的事情让你的js使用react-router来做。

参考:https://webpack.js.org/configuration/dev-server/#devserver-historyapifallback

这适用于任何 react-router

您必须添加 historyApiFallback: true

module.exports = {
    cache: true,
    entry: "./index.js",
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'public')
    },
    context: SRC,
    devServer: {
        contentBase: path.resolve(__dirname, 'public/assets'),
        stats: 'errors-only',
        open: true,
        port: 8080,
        compress: true,
        historyApiFallback: true
    },
...
}
output: {
    ...
    publicPath: "/"
  },

添加 public 路径为我解决了这个问题

我遇到了这个问题,只能使用 index: '/' 和 webpack 4.20.2

来修复它
        historyApiFallback: {
            index: '/'
        }

这里发生了一件非常棘手的事情!

404 可以是下面两个完全不同的。可以打开Chrome的Network标签,看看是初始请求404,还是里面的assets。

如果不怕终端的话,也可以curl -v http://localhost:8081/product看看实际的HTTP响应码

案例 1:初始 HTML 页面上的 404

这是historyFallbackApi设置不正确的情况。

通常只有 historyApiFallback: true 应该在 Webpack 的 devServer 配置中工作。 (source) Yet, if you happen to have a custom output folder, you have to set the index property of historyApiFallback to the same path, as advised by the other answers on this question like or .

案例 2:资产上的 404(例如 bundle.jsvendor.js

这个很有意思!

在这种情况下,您实际上得到了初始 HTML(即,如果您在 URL 之前添加 view-source: 成为 view-source:http://localhost:8081/admin,您会看到 HTML、and/or curl 命令显示 HTML),但该页面在浏览器中不起作用。

historyApiFallback 所做的,听起来像是魔术,实际上只是将 Express 服务器的 req.url 设置为 index.html 文件,因为域内的任何传入 GET 请求。 (The main two lines in the Source Code)

但是,如果您的资产路径是相对的(例如,在查看源代码中,您会看到 <script src="vendor.js"></script>AND 您登陆的路径不是在与索引相同的路径深度(例如,当主服务器处于 http://localhost:8081/admin 时,您试图加载 http://localhost:8081/admin/user/12/summary),发生的事情是它找不到您的 JavaScript 的 .js 文件代码。 (在我的例子中 http://localhost:8081/admin/user/12/vendor.js

请注意,这里处理 HTML5 历史记录的任何路由器(反应路由器或 vue 路由器)都知道如何在初始加载时将内部路径初始化为 document.location.href。但是,它不知道正确更新资产路径的“根”在哪里。 (就责任而言,这甚至可能不是它的工作。)因此,资产的路径将根据 URL 的路径计算,而不是 index.html 的路径!因此,对于没有绝对 / 前缀的 src="vendor.js",它会尝试查找 /admin/user/12/vendor.js 而不是 /vendor.js.

这里你需要做的是确保你的WebPack的output路径是绝对路径并且以/开头,所以不管着陆URL,它总是有效的。即在 HTML 来源中总是 <script src="/vendor.js"></script>

为此,您必须将 output.publicPath 设置为绝对路径(有或没有域)。您可以通过上面的 view-source:curl 技术来验证这一点。 :)

如果您发现某些 路径有效而其他路径无效,您可能违反了“点规则”。每 the docs:

When using dots in your path (common with Angular), you may need to use the disableDotRule:

webpack.config.js

module.exports = {
  //...
  devServer: {
    historyApiFallback: {
      disableDotRule: true,
    },
  },
};