create-react-app

近期,趁着空闲时间,学习了下react的相关知识,对于配置问题,为了方便快速上手,就采用了官方的create-react-app来配置环境。期间遇到不少问题。总结一下。

项目基本完成,还有一些需要小优化。展示链接http://luckyp.top/cnode/,备用链接https://rcnode.luckyp.top/

写在前面

对于react来说,需要注意的就是它的生命周期问题,网上有大量的资料,一幅图简单的说明如下

component-lifecycle.jpg

生命周期 调用次数 能否使用 setSate()
getDefaultProps 1(全局调用一次)
getInitialState 1
componentWillMount 1
render >=1
componentDidMount 1
componentWillReceiveProps(nextProps) >=0
shouldComponentUpdate(nextProps,nextState) >=0
componentWillUpdate(nextProps,nextState) >=0
componentDidUpdate(prevProps,prevState) >=0
componentWillUnmount 1

create-react-app

配置文件

为了方便使用,create-react-app提供了直接暴露配置文件的方法,如下

1
npm run eject

当然是单向不可逆操作的,为了尽可能的减少改变源码的操作,使用了另外一种办法,通过react-app-rewired

1
npm install react-app-rewired --save-dev

简单的使用方式就是在根目录创建一个config-overrides.js文件,调整package.json的默认配置。详细配置见github。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* config-overrides.js */
module.exports = function override(config, env) {
//do stuff with the webpack config...
return config;
}
/* package.json */
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test --env=jsdom",
+ "test": "react-app-rewired test --env=jsdom"
}

github pages部署

homepage设置

在项目完成之后,打包,通过的也是npm run build(同yarn run build),如果直接上传到github服务器托管会存在路径问题,这里查看文档可以知道。需要在package.json中设置

1
"homepage": "http://mywebsite.com/relativepath",

如果没有托管的服务器地址,也可以设置为

1
"homepage":"."

项目页面设置

因为上传的GitHub用户页面被博客占用,所以只能使用项目页面,需要添加gh-pages

1
2
3
4
5
6
7
8
npm install --save gh-pages

/* package.json */
"scripts": {
+ "predeploy": "npm run build",
+ "deploy": "gh-pages -d build",
"start": "react-app-rewired start",
"build": "react-app-rewired build",

npm run deploy会执行predeploy,同时上传创建github的分支,默认gh-pages分支。进入项目主页,设置gh-pages分支展示为page即可。

这时候页面的展示地址应该是https://myusername.github.io/project-name

路由设置

因为使用react-router@^4,所以还需要设置在<Router>中设置basename,该值为你的项目名称。这里我的项目是名称是cnode

可以新建一个文件,然后导出,判断是否为开发环境,以便用于域名的二级目录。

1
2
3
let basename = process.env.NODE_ENV === 'production' ? '/cnode' : '';

export default basename

因为需要部署到github,而GitHub Pages存在一个问题,不支持pushState引擎盖下使用HTML5 历史API的路由器(例如,使用React Router browserHistory)。因为在https://myusername.github.io/project-name/topics中,/topics属于前端部分,后端获取不到,会报404错误。

这里有两种解决方式,一种就是通过重定向,当404时,跳转你设置好的页面,另一种就是使用hashHistory,不过存在的问题是,路径过长,这里我采用的是第二种方法。

------本文结束 感谢阅读------