您的位置:首页 > Web前端 > React

react-router打包后打开路由页面空白

2017-12-12 14:47 3895 查看
react-router打包后无法通过路由进入到页面,是因为当我们使用react-router-dom里的BrowserRouter as Router时,是用浏览器history对象的方法去请求服务器,

如果服务器没有相对于的路由去指向对应的页面路由会找不到资源。

BrowserRouter会变成类似这样的路径  http://111.230.139.105:3001/detail/9459469,这样的路径在访问服务器时,服务器会认为是请求查找某个接口数据

This request URL /detail/9459469 was not found on this server.


所以这时候必须使用HashRouter,这时候访问具体页面时就是http://111.230.139.105:3001/#/detail/9459469

import { HashRouter as Router, Route } from 'react-router-dom'
import createHistory from 'history/createHashHistory'
const history = createHistory()

<Router history={history}>
<Route render={({ location }) => {
return(
<div>
<Route location={location} exact path="/" component={Home} />
<Route location={location} path="/detail/:id" component={Detail} />
<Route location={location} path="/comment/:id" component={Comment} />
</div>
)}}/>
</Router>


 

webpack打包时要添加NODE_ENV,并且将devtool:'eval-source-map',去除,不然build出来的js特别大,source map是为了代码出错后采用source-map的形式直接显示你出错代码的位置

打包生产包时去除,加上这两个后大部分简单单页面应用会在100k到200k

new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),


// devtool:'eval-source-map',
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: