極客園PC-第5章 專案打包與效能優化
阿新 • • 發佈:2022-03-24
專案打包
專案打包和釋出
- 專案打包:
yarn build
( build 構建 )- 打包後的內容放在
build
目錄中 - 專案上線,就是將 build 目錄中的內容,放到伺服器中即可
- 打包後的內容放在
yarn build 打包
yarn global add serve
serve -s build //啟動打包的服務
按需載入
- 效能優化:
- 實現
按需載入
:訪問哪個頁面才去載入這個頁面的 JS 檔案,而不是第一次訪問網站就把網站中的 JS 檔案一次性全部載入 - 按需載入:第一次開啟網站,載入的內容少,速度快
- 一次性全部載入:第一次開啟網站,載入的內容多,速度慢,使用者減少
- 程式碼分隔
- 實現
// 使用之前:
import OtherComponent from './OtherComponent';
// 只要將匯入元件的方式,換成下面這種即可:
// 使用之後:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
- 程式碼修改:
const Login = React.lazy(() => import('pages/Login')) const Layout = React.lazy(() => import('pages/Layout')) {/* 路由規則 */} <Suspense fallback={ <div style={{ textAlign: 'center', marginTop: 200, }} > loading... </div> } > <Switch> <Redirect exact from="/" to="/home"></Redirect> <AuthRoute path="/home" component={Layout}></AuthRoute> <Route path="/login" component={Login}></Route> </Switch> </Suspense>