Skip to content

Commit

Permalink
refactor: change to use antd SSR plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
Carrotzpc committed Jul 30, 2024
1 parent 7ce3068 commit e0c41de
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 27 deletions.
2 changes: 1 addition & 1 deletion example/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "dumi-theme-yunti-example",
"scripts": {
"bp": "PREVIEW=true dumi build && dumi preview",
"bp": "PREVIEW=true npm run build:no-compress && npm run preview",
"build": "dumi build",
"build:analyze": "ANALYZE=1 dumi build",
"build:no-compress": "COMPRESS=none dumi build",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@
},
"dependencies": {
"@ant-design/cssinjs": "^1.21.0",
"@emotion/css": "^11.13.0",
"@emotion/server": "^11.11.0",
"@floating-ui/react": "^0.26.17",
"ahooks": "^3.8.0",
Expand All @@ -91,6 +90,7 @@
"antd-style": "^3.6.2",
"clean-pkg-json": "^1.2.0",
"commitlint": "^18",
"dumi": "^2.4.7",
"dumi-assets-types": "^2.3.0",
"eslint": "^8.57.0",
"father": "4.3.1",
Expand Down
12 changes: 6 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 4 additions & 6 deletions src/layouts/GlobalLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// import { isBrowser } from '@/utils';
import {
StyleProvider,
createCache,
Expand All @@ -11,12 +12,9 @@ import { useLocation, useOutlet, useServerInsertedHTML } from 'dumi';
import type { FC } from 'react';
import React from 'react';

import { useAdditionalThemeConfig } from '../hooks/useAdditionalThemeConfig';

const GlobalLayout: FC = () => {
const { pathname } = useLocation();
const outlet = useOutlet();
const { ssr } = useAdditionalThemeConfig();
const [styleCache] = React.useState(() => createCache());

useServerInsertedHTML(() => {
Expand Down Expand Up @@ -52,9 +50,9 @@ const GlobalLayout: FC = () => {
content = <App>{outlet}</App>;
}

if (ssr) {
(global as any).styleCache = styleCache;
}
// if (!isBrowser) {
// (global as any).styleCache = styleCache;
// }

return (
<StyleProvider
Expand Down
53 changes: 40 additions & 13 deletions src/plugin/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
import { extractStaticStyle } from 'antd-style';
// import { extractStaticStyle } from 'antd-style';
import createEmotionServer from '@emotion/server/create-instance';
import chalk from 'chalk';
import type { IApi } from 'dumi';
import fs from 'node:fs';
import path from 'node:path';

import { getHash } from './utils';

function extractEmotionStyle(html: string) {
// copy from emotion ssr
// https://github.com/vercel/next.js/blob/deprecated-main/examples/with-emotion-vanilla/pages/_document.js
const styles = global.__ANTD_STYLE_CACHE_MANAGER_FOR_SSR__.getCacheList().map(cache => {
const result = createEmotionServer(cache).extractCritical(html);
if (!result.css) {
return null;
}

const { css, ids } = result;

return {
key: cache.key,
css,
ids,
tag: `<style data-emotion="${cache.key} ${result.ids.join(' ')}">${result.css}</style>`,
};
});
return styles.filter(Boolean);
}

const SSRPlugin = (api: IApi) => {
// const ssrCssFileName = `ssr-${Date.now()}.css`;

// api.describe({
// key: '@',
// });
Expand All @@ -28,13 +52,6 @@ const SSRPlugin = (api: IApi) => {
api.logger.info('detect ssr config, when building html will extract css.');

// add ssr css file to html
api.modifyConfig(memo => {
// 将 .dumrc 中 ssr 配置注入 themeConfig 中,便于页面获取
memo.themeConfig.ssr = memo.ssr;

return memo;
});

const writeCSSFile = (key: string, hashKey: string, cssString: string) => {
const fileName = `ssr-${key}.${getHash(hashKey)}.css`;

Expand All @@ -60,25 +77,35 @@ const SSRPlugin = (api: IApi) => {
.filter(f => !f.path.includes(':'))

.map(file => {
const antdCache = (global as any).__ANTD_CACHE__;
// const antdCache = (global as any).__ANTD_CACHE__;
// const styles = extractStaticStyle(file.content, { antdCache });

const styles = extractStaticStyle(file.content, { antdCache });
// 1. 提取 antd-style 样式
const styles = extractEmotionStyle(file.content);

for (const result of styles) {
api.logger.event(
`${chalk.yellow(file.path)} include ${chalk.blue`[${result.key}]`} ${chalk.yellow(
result.ids.length
`${chalk.yellow(file.path)} include ${chalk.blue`[${result!.key}]`} ${chalk.yellow(
result!.ids.length
)} styles`
);

const cssFile = writeCSSFile(result.key, result.ids.join(''), result.css);
const cssFile = writeCSSFile(result!.key, result!.ids.join(''), result!.css);

file.content = addLinkStyle(file.content, cssFile);
}

return file;
})
);

// add ssr css file to html
api.modifyConfig(memo => {
memo.styles ??= [];
// memo.styles.push(`/${ssrCssFileName}`);

return memo;
});
};

export default SSRPlugin;

0 comments on commit e0c41de

Please sign in to comment.