我需要一些关于如何使用React-router与浏览器历史记录和Webpack的帮助。一切正常,直到我需要使用嵌套路线,就在我的bundle.js上获得404时。
没有历史记录(在网址中使用#s)一切正常,但我宁愿没有它们。我甚至使用代理服务器(下面的代码),这确实解决了问题,但也意味着我似乎无法使用我需要的所有其他Webpack(如postcss等)。至少我不知道怎么做。
所以我真的想让这个东西使用Webpack来处理我的postcss,React-router有漂亮干净的网址和嵌套路由。到目前为止看起来并不太有希望......
这是我的webpack配置文件(es6语法):
import path from 'path';
import HtmlwebpackPlugin from 'html-webpack-plugin';
import merge from 'webpack-merge';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import postcssImport from 'postcss-import';
import nested from 'postcss-nested';
import mqpacker from 'css-mqpacker';
import cssnext from 'postcss-cssnext';
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = path.resolve(__dirname);
const APP_PATH = path.resolve(ROOT_PATH, 'app');
const BUILD_PATH = path.resolve(ROOT_PATH, 'public');
const common = {
entry: [
APP_PATH + '/App.js',
],
output: {
path: BUILD_PATH,
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
},
{
test: /\.css$/,
/* loader: 'style-loader!css-loader!postcss-loader',*/
loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap!postcss-loader'),
},
],
},
postcss: function(webpack) {
return [
postcssImport({
addDependencyTo: webpack,
}),
nested,
mqpacker,
cssnext(),
];
},
};
if (TARGET === 'dev' || !TARGET) {
module.exports = merge(common, {
devtool: 'inline-source-map',
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
},
plugins: [
new ExtractTextPlugin('app.css'),
new HtmlwebpackPlugin({
title: 'Hohohohoho',
template: BUILD_PATH + '/index.html',
inject: 'body',
}),
],
});
}
...哪个正常,但无法使用嵌套路由。接下来又是我尝试使用node并使其工作的东西,但是随后使用带有Webpack的postcss失败了:
require('babel/register')({});
var server = require('pushstate-server');
server.start({
port: process.env.PORT || 8090,
directory: './public'
});
var WebpackDevServer = require("webpack-dev-server");
var webpack = require("webpack");
var compiler = webpack(process.argv[2] == 'hot' ? require('./webpack.config.hot.js') : require('./webpack.config.babel.js'));
var devServer = new WebpackDevServer(compiler, {
stats: {colors: true},
contentBase: 'http://localhost:8090/',
publicPath: 'http://localhost:8080/js/',
hot: process.argv[2] == 'hot'
});
devServer.listen(8080, "localhost", function() {})
有人告诉我使用historyApiFallback,但似乎根本没有改变任何东西,但它仍然存在于webpack选项中。
答案 0 :(得分:0)
您需要做的就是在路由器中添加history
参数:
import React from 'react'
import { render } from 'react-dom'
import { Router } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
const history = createBrowserHistory()
render((
<Router history={history}>
{/* some routes */}
</Router>
), document.getElementById('root'));
有关文档中createBrowserHistory()
的更多信息。
确保您安装了history
模块:npm install history
。