从两个不同的静态构建目录提供 React 构建文件

Serve React build files from two different static build directories

我目前正在创建一个反应网页,使用 starlette 作为我的网络服务器框架,连接我的数据库并提供 API。为了改进代码分离和不需要的文件加载,我将我的页面分成两个单独构建的 React 页面。一个用于验证前的登录页面,一个用于验证完成且用户拥有有效令牌后的主页。这样做的问题是,两个 React 网页都将 GET 请求作为示例发送到:/static/js/2.91da4595.chunk.js

我想知道是否可以更改在查找静态文件时 React 将请求发送到的位置。因此,例如我的登录页面将改为 /otherstatic/js/2.91da4595.chunk.js

可能有更优雅的方法可以达到我想要的目的,所以请随时提出不同的方法。如果需要任何进一步的解释或代码,请告诉我,我可以将其添加到此 post。

您可能需要进行代码拆分。阅读 here 了解更多信息。

Code-splitting your app can help you “lazy-load” just the things that are currently needed by the user, which can dramatically improve the performance of your app. While you haven’t reduced the overall amount of code in your app, you’ve avoided loading code that the user may never need, and reduced the amount of code needed during the initial load.

我假设你使用了 react-router-dom,所以这是一个简单的实现:

import React, { Suspense } from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';

const HomePage = React.lazy(() => import('./HomePage'));
const LoginPage = React.lazy(() => import('./LoginPage'));

function MyApp() {
  const [auth, setAuth] = React.useState({
    isLoading: true,
    isAuthenticated: false,
    data: null,
  })

  React.useEffect(() => {
    const checkAuth = () => {
      // call setAuth here
    }

    checkAuth()
  }, [])

  const MyRoute = ({ component: Component, authorized: false, ...rest }) => (
    <Route
      {...rest}
      render={props => {
        if (auth.isLoading) return null
        if (authorized) { // Home page access
          return auth.isAuthenticated
            ? <Component {...prop} />
            : <Redirect to="/login" />
        } else { // Login page access
          return !auth.isAuthenticated
            ? <Component {...prop} />
            : <Redirect to="/" />
        }
      }}
    />
  )

  return (
    <BrowserRouter>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <MyRoute path="/login" component={LoginPage} authorized={false} />
          <MyRoute path="/" component={HomePage} authorized={true} />
        </Switch>
      </Suspense>
    </BrowserRouter>
  );
}