Skip to content

Commit

Permalink
improve bunddle size
Browse files Browse the repository at this point in the history
  • Loading branch information
MrWangJustToDo committed Dec 26, 2021
1 parent 0e3a15e commit e95a18b
Show file tree
Hide file tree
Showing 12 changed files with 479 additions and 493 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ module.exports = {
"jsx-a11y/anchor-is-valid": "off",

// Why would you want unused vars?
"@typescript-eslint/no-unused-vars": ["error"],
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],

// I suggest this setting for requiring return types on functions only where useful
"@typescript-eslint/explicit-function-return-type": [
Expand Down
16 changes: 8 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-ssr",
"version": "1.1.3",
"version": "1.1.4",
"author": "mrwang",
"license": "MIT",
"scripts": {
Expand Down Expand Up @@ -43,7 +43,7 @@
"redux-thunk": "^2.4.1",
"spark-md5": "^3.0.1",
"webpack": "^5.65.0",
"zustand": "^3.6.7"
"zustand": "^3.6.8"
},
"devDependencies": {
"@babel/cli": "^7.16.0",
Expand Down Expand Up @@ -72,10 +72,10 @@
"@types/loadable__server": "^5.12.3",
"@types/lodash": "^4.14.178",
"@types/multer": "^1.4.7",
"@types/node": "^17.0.2",
"@types/react": "^17.0.37",
"@types/node": "^17.0.4",
"@types/react": "^17.0.38",
"@types/react-dom": "^17.0.11",
"@types/react-redux": "^7.1.16",
"@types/react-redux": "^7.1.21",
"@types/webpack": "^5.28.0",
"@types/webpack-dev-middleware": "^5.0.2",
"@types/webpack-env": "^1.16.3",
Expand All @@ -86,15 +86,15 @@
"babel-loader": "^8.2.2",
"babel-plugin-import": "^1.13.3",
"clean-webpack-plugin": "^4.0.0",
"core-js": "^3.20.0",
"core-js": "^3.20.1",
"cross-env": "^7.0.3",
"css-loader": "^6.5.1",
"css-minimizer-webpack-plugin": "^3.3.1",
"eslint": "^8.5.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.27.0",
"eslint-plugin-react": "^7.28.0",
"eslint-plugin-react-hooks": "^4.3.0",
"eslint-webpack-plugin": "^3.1.1",
"file-loader": "^6.2.0",
Expand All @@ -114,7 +114,7 @@
"webpack-bundle-analyzer": "^4.4.0",
"webpack-cli": "^4.5.0",
"webpack-dev-middleware": "^5.3.0",
"webpack-dev-server": "^4.7.0",
"webpack-dev-server": "^4.7.1",
"webpack-hot-middleware": "^2.25.1",
"webpack-manifest-plugin": "^4.0.2",
"webpack-merge": "^5.7.3",
Expand Down
29 changes: 15 additions & 14 deletions src/client/chakraEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,22 @@ const cache = createEmotionCache();
const Root = ({ store }: { store: ReturnType<typeof createUniversalStore> }) => {
console.warn("you are using chakra UI component library!");

/* for chakra UI always have id not match issue on the develop mode */
return (
// <React.StrictMode> for chakra UI always have id not match issue on the develop mode
<CacheProvider value={cache}>
<ChakraProvider resetCSS>
<Provider store={store}>
<Router>
<HelmetProvider>
<ColorModeScript />
<App />
</HelmetProvider>
</Router>
</Provider>
</ChakraProvider>
</CacheProvider>
// </React.StrictMode>
<React.StrictMode>
<CacheProvider value={cache}>
<ChakraProvider resetCSS>
<Provider store={store}>
<Router>
<HelmetProvider>
<ColorModeScript />
<App />
</HelmetProvider>
</Router>
</Provider>
</ChakraProvider>
</CacheProvider>
</React.StrictMode>
);
};

Expand Down
33 changes: 23 additions & 10 deletions src/client/entry.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import React from "react";
import { hydrate, render } from "react-dom";
import { loadableReady } from "@loadable/component";
Expand All @@ -6,30 +7,42 @@ import { createUniversalStore } from "store";
import { log } from "utils/log";
import { safeData } from "utils/safeData";
import { StoreState } from "types/store";
import { Root as AntRoot } from "./antDesignEntry";
import { Root as ChakraRoot } from "./chakraEntry";
import { Root as MaterialRoot } from "./materialEntry";

const place = document.querySelector("#__content__");

const preLoadEnvElement = document.querySelector("script#__preload_env__");

const preLoadStateElement = document.querySelector("script#__preload_state__");

const store = createUniversalStore({ initialState: JSON.parse(preLoadStateElement?.innerHTML || "") as StoreState });
const store = createUniversalStore({ initialState: JSON.parse(preLoadStateElement?.innerHTML || "{}") as StoreState });

window.__ENV__ = safeData(JSON.parse(preLoadEnvElement?.innerHTML || "{}"));

safeData(window as unknown as Record<string, unknown>, "__ENV__");

const Root = window.__ENV__.UI === "material" ? MaterialRoot : window.__ENV__.UI === "antd" ? AntRoot : ChakraRoot;
let Root = ({ store: _store }: { store: ReturnType<typeof createUniversalStore> }) => <></>;

// multiple UI component
if (__UI__ === "antd") {
const { Root: originalRoot } = require("./antDesignEntry");
Root = originalRoot;
}
if (__UI__ === "chakra") {
const { Root: originalRoot } = require("./chakraEntry");
Root = originalRoot;
}
if (__UI__ === "material") {
const { Root: originalRoot } = require("./materialEntry");
Root = originalRoot;
}

if (!window.__ENV__.SSR) {
loadableReady(() => render(<Root store={store} />, place));
} else {
loadableReady(() =>
__DEVELOPMENT__ && __MIDDLEWARE__
? (log("not hydrate render on client", "warn"), render(<Root store={store} />, place))
: hydrate(<Root store={store} />, place)
);
if (__DEVELOPMENT__ && __MIDDLEWARE__) {
log("not hydrate render on client", "warn");
loadableReady(() => render(<Root store={store} />, place));
} else {
loadableReady(() => hydrate(<Root store={store} />, place));
}
}
3 changes: 1 addition & 2 deletions src/components/UI.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import React from "react";
import { getUniverSalUI } from "utils/universal";

export function UI() {
return (
<div>
<h3>当前UI Component: {getUniverSalUI()}</h3>
<h3>当前UI Component: {__UI__}</h3>
</div>
);
}
3 changes: 1 addition & 2 deletions src/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ declare const __DEVELOPMENT__: boolean;
declare const __MIDDLEWARE__: boolean;
declare const __ANIMATE_ROUTER__: boolean;
declare const __BUILD_TIME__: string;
declare const PUBLIC_API_HOST: string;
declare const ANIMATE_ROUTER: boolean;
declare const __UI__: "material" | "antd" | "chakra";

interface Window {
__cache: unknown;
Expand Down
21 changes: 11 additions & 10 deletions src/router/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,30 @@ import { Layout } from "components/Layout";
import { UI } from "components/UI";
import { filter } from "./tools";
import { dynamicRouteConfig } from "./dynamicRoutes";
import { getUniverSalUI } from "utils/universal";
import { PreLoadRouteConfig } from "types/router";

const LoadAble_I18n = loadable<unknown>(() => import("../components/i18n"));
const LoadAble_Antd = loadable<unknown>(() => import("../components/antDesignComponent"));
const LoadAble_Chakra = loadable<unknown>(() => import("../components/chakraComponent"));
const LoadAble_Material = loadable<unknown>(() => import("../components/materialComponent"));

const baseRouter: PreLoadRouteConfig = {
element: <Layout />,
Component: Layout,
};

const currentUI = getUniverSalUI();
let LoadAble_UI: ReturnType<typeof loadable> | (() => JSX.Element) = () => <></>;
if (__UI__ === "antd") {
LoadAble_UI = loadable<unknown>(() => import("../components/antDesignComponent"));
}
if (__UI__ === "material") {
LoadAble_UI = loadable<unknown>(() => import("../components/materialComponent"));
}
if (__UI__ === "chakra") {
LoadAble_UI = loadable<unknown>(() => import("../components/chakraComponent"));
}

export const routes: PreLoadRouteConfig[] = [
{ path: "/", element: <UI />, Component: UI },
{ path: "/i18n", element: <LoadAble_I18n />, Component: LoadAble_I18n },
currentUI === "antd"
? { path: "/antd", element: <LoadAble_Antd />, Component: LoadAble_Antd }
: currentUI === "material"
? { path: "/material", element: <LoadAble_Material />, Component: LoadAble_Material }
: { path: "/chakra", element: <LoadAble_Chakra />, Component: LoadAble_Chakra },
{ path: __UI__ === "antd" ? "/antd" : __UI__ === "material" ? "/material" : "chakra", element: <LoadAble_UI />, Component: LoadAble_UI },
];

const dynamicRoutes = dynamicRouteConfig
Expand Down
4 changes: 1 addition & 3 deletions src/server/middleware/renderPage/middleware/globalEnv.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { getUniverSalUI } from "utils/universal";
import { Middleware } from "../compose";

export const globalEnv: Middleware = (next) => async (args) => {
const { PUBLIC_API_HOST, ANIMATE_ROUTER, SSR, CRYPTO_KEY } = process.env;
const UI = getUniverSalUI();
args.env = { PUBLIC_API_HOST, ANIMATE_ROUTER: JSON.parse(ANIMATE_ROUTER), SSR: JSON.parse(SSR), CRYPTO_KEY, UI };
args.env = { PUBLIC_API_HOST, ANIMATE_ROUTER: JSON.parse(ANIMATE_ROUTER), SSR: JSON.parse(SSR), CRYPTO_KEY, UI: __UI__ };

await next(args);
};
21 changes: 12 additions & 9 deletions src/server/middleware/renderPage/renderSSR/index.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { ServerError } from "server/utils/error";
import { AnyAction, composeRender } from "../compose";
import { globalEnv, initLang, initStore, loadLang, loadStore } from "../middleware";
import { targetRender as antDesignRender } from "./renderAntDesign";
import { targetRender as materialRender } from "./renderMaterial";
import { targetRender as chakraRender } from "./renderChakra";

const targetRender: AnyAction = async ({ req, res, store, lang, env }) => {
if (!store || !lang || !env) {
throw new ServerError("初始化失败", 500);
} else {
if (env.UI === "antd") {
return antDesignRender({ req, res, store, lang, env });
} else if (env.UI === "material") {
return materialRender({ req, res, store, lang, env });
} else {
return chakraRender({ req, res, store, lang, env });
if (__UI__ === "antd") {
const { targetRender } = require("./renderAntDesign");
return targetRender({ req, res, store, lang, env });
}
if (__UI__ === "material") {
const { targetRender } = require("./renderMaterial");
return targetRender({ req, res, store, lang, env });
}
if (__UI__ === "chakra") {
const { targetRender } = require("./renderChakra");
return targetRender({ req, res, store, lang, env });
}
}
};
Expand Down
9 changes: 0 additions & 9 deletions src/utils/universal.ts

This file was deleted.

8 changes: 4 additions & 4 deletions webpack/plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ const ESLintPlugin = require("eslint-webpack-plugin");
// 查看打包
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

const UI = process.env.UI;
const currentUI = UI === "antd" || UI === "material" || UI === "chakra" ? UI : "material";

const pluginsConfig = ({ env, isDev = true, isSSR = true, isMiddleWareDevelop = false, isAnimationRouter = false }) => {
return [
new CleanWebpackPlugin(),
Expand All @@ -28,6 +31,7 @@ const pluginsConfig = ({ env, isDev = true, isSSR = true, isMiddleWareDevelop =
__MIDDLEWARE__: isMiddleWareDevelop,
__ANIMATE_ROUTER__: isAnimationRouter,
__BUILD_TIME__: JSON.stringify(new Date().toLocaleString()),
__UI__: JSON.stringify(currentUI),
}),
env === "client" &&
new MiniCssExtractPlugin({
Expand All @@ -42,10 +46,6 @@ const pluginsConfig = ({ env, isDev = true, isSSR = true, isMiddleWareDevelop =
env === "client" &&
new ForkTsCheckerWebpackPlugin({
async: false,
// logger: {
// infastructure: "silent",
// issues: "console",
// },
}),
env === "client" &&
new ESLintPlugin({
Expand Down
Loading

0 comments on commit e95a18b

Please sign in to comment.