React SPA学习(二)
针对(一)中的开始项目,继续
一、通过react-router构建项目导航
阮老师推荐的react-router学习demo:https://github.com/reactjs/react-router-tutorial
- react-router 是一个组件
- Router history属性值之hashHistory,url中有junk info
- Link标签:Link标签不同于a标签的一点是,Link标签可以感知他link的链接是否激活 activeStyle={{ color: 'red' }}/activeClassName="active"
- url嵌套和对应的组件嵌套相对应
- /repos/:userName/:repoName路由的组件中可通过this.props.params[name]获取值
webpack dev server不是一个生产环境下的服务器,通过lession 11搭建生产环境下的服务器:
1.添加Express、if-env、compression模块依赖,通过Express构建生产环境:
npm install express if-env compression --save-de
2.在项目根目录添加server.js文件,用于启动Express
// server.js const express = require('express'); const path = require('path'); const compression = require('compression'); const app = express(); app.use(compression()); // serve our static stuff like index.css app.use(express.static(path.join(__dirname, 'public/dist'))); // send all requests to index.html so browserHistory in React Router works app.get('*', function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')) }); const PORT = process.env.PORT || 8080; app.listen(PORT, function() { console.log('Production Express server running at localhost:' + PORT) });
- app.use(express.static(path.join(__dirname, 'public/dist')));学习推荐阅读:http://www.cnblogs.com/A-dam/p/5053299.html
- app.use是用来给path注册中间函数的,这个path默认是'/',也就是处理任何请求,同时他会处理path下的子路径
- 将静态资源文件路径设置为项目目录+/public/dist,即所有请求先交给express.static处理下
- Express 会在静态资源目录下查找文件,所以不需要把静态目录作为URL的一部分。
- webpack.config.js文件中output字段属性publicPath的设置不影响生产环境下资源文件的访问,因为所有资源访问都通过Express服务器响应,影响通过webpack-dev-server启动的开发环境对资源的访问
- app.get('*', function(){ ...index.html})通过将所有的请求都响应index.html文件来使react-router的browserHistory生效,当刷新页面或点击浏览器的回退都能正常响应
3.对public路径下的index.html文件对bundle.js文件的引用路径进行修改:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>RSPA</title> </head> <body> <div id="wrapper"></div> <script type="text/javascript" src="/bundle.js"></script> </body> </html>
4.修改package.json中的script字段,注意start:dev中的--content-base public的设置
"scripts": { "start": "if-env NODE_ENV=production && npm run start:dist || npm run start:dev", "start:dev": "webpack-dev-server --inline --content-base public --history-api-fallback --process --colors", "start:dist": "webpack && node server.js", "hot": "webpack-dev-server --hot --inline --history-api-fallback --progress --colors" },
5.修改webpack.config.js中的output字段publicPath属性值为‘/’,虚拟目录,自动指向path编译目录,学习阅读:http://www.cnblogs.com/yueliangcl/p/6679427.html
output: { path: BUILD_PATH, filename: '[name].js', publicPath: '/' }
6.通过git bash启动生产环境命令/开发环境命令
NODE_ENV=production npm start
NODE_ENV=dev npm start
至此,生产环境支持browseHistory路由策略的react-router环境搭建完毕。