閑來無事,就想著把前幾天折騰的問題重新梳理一遍,加深印象.
上面一篇文章有提到升級eject
的cra
項目.為什么升級這個項目,就是想要折騰,就是想要使用到webpack2
,還有一個好處是加深對create-react-app
的理解.壞處不言而喻,折騰浪費生命浪費時間.
按需加載
AsyncComponent.js
import React, { Component } from "react";
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render() {
const Component = this.state.component;
return Component ? <Component {...this.props} /> : null;
}
}
return AsyncComponent;
}
這個是異步加載組件的方法.到時在需要的組件上加入引用就好.例如在路由里.
Menu.js
const AsyncUser = asyncComponent(() => import("./User"));
...
<Route path="/users" component={AsyncUser}/>
部署(nginx以及npm2)
-
nginx
- 準(zhǔn)備工作
npm run build
sudo vim /etc/nginx/sites-enabled/react-app.conf
server { listen 7878; server_name 127.0.0.1; root /home/deploy/workspace/project/build; location / { try_files $uri /index.html; add_header Cache-Control no-cache; #expires 1d; } }
- 啟用nginx配置
sudo service nginx reload sudo service nginx restart
- 注意
如果是阿里云服務(wù)器,可能訪問失敗,阿里云的安全策略默認(rèn)是只開啟了80
端口,首先去實例里檢測其他的端口是否開放.
-
pm2
-
installl and start
sudo npm install pm2 -g pm2 start npm -- start
-
nginx
# sudo vim /etc/nginx/sites-available/react-app.conf server{ listen 80 default_server; server_name YOUR-SERVER-NAME; location / { proxy_pass http://localhost:3000; #or any port number here proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
-
restart
sudo service nginx reload sudo service nginx restart
-