Browse Source

chore: try cache

docs/rm-emotion-react
MadCcc 1 year ago
parent
commit
119198d433
  1. 6
      .dumi/theme/layouts/GlobalLayout.tsx
  2. 65
      .dumi/theme/plugin.ts
  3. 1
      package.json

6
.dumi/theme/layouts/GlobalLayout.tsx

@ -3,12 +3,12 @@ import {
legacyNotSelectorLinter, legacyNotSelectorLinter,
logicalPropertiesLinter, logicalPropertiesLinter,
parentSelectorLinter, parentSelectorLinter,
StyleProvider,
} from '@ant-design/cssinjs'; } from '@ant-design/cssinjs';
import { App, theme as antdTheme } from 'antd'; import { App, theme as antdTheme } from 'antd';
import type { DirectionType } from 'antd/es/config-provider'; import type { DirectionType } from 'antd/es/config-provider';
import { createSearchParams, useOutlet, useSearchParams } from 'dumi'; import { createSearchParams, useOutlet, useSearchParams } from 'dumi';
import React, { useCallback, useEffect, useMemo } from 'react'; import React, { useCallback, useEffect, useMemo } from 'react';
import { StyleProvider as AntdStyleProvider } from 'antd-style';
import useLayoutState from '../../hooks/useLayoutState'; import useLayoutState from '../../hooks/useLayoutState';
import SiteThemeProvider from '../SiteThemeProvider'; import SiteThemeProvider from '../SiteThemeProvider';
import useLocation from '../../hooks/useLocation'; import useLocation from '../../hooks/useLocation';
@ -108,7 +108,7 @@ const GlobalLayout: React.FC = () => {
); );
return ( return (
<StyleProvider <AntdStyleProvider
cache={styleCache} cache={styleCache}
linters={[logicalPropertiesLinter, legacyNotSelectorLinter, parentSelectorLinter]} linters={[logicalPropertiesLinter, legacyNotSelectorLinter, parentSelectorLinter]}
> >
@ -132,7 +132,7 @@ const GlobalLayout: React.FC = () => {
</App> </App>
</SiteThemeProvider> </SiteThemeProvider>
</SiteContext.Provider> </SiteContext.Provider>
</StyleProvider> </AntdStyleProvider>
); );
}; };

65
.dumi/theme/plugin.ts

@ -2,9 +2,16 @@ import { extractStyle } from '@ant-design/cssinjs';
import type { IApi, IRoute } from 'dumi'; import type { IApi, IRoute } from 'dumi';
import ReactTechStack from 'dumi/dist/techStacks/react'; import ReactTechStack from 'dumi/dist/techStacks/react';
import fs from 'fs'; import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import sylvanas from 'sylvanas'; import sylvanas from 'sylvanas';
import { extractStaticStyle } from 'antd-style';
import { createHash } from 'crypto';
import localPackage from '../../package.json'; import localPackage from '../../package.json';
export const getHash = (str: string, length = 8) =>
createHash('md5').update(str).digest('hex').slice(0, length);
/** /**
* extends dumi internal tech stack, for customize previewer props * extends dumi internal tech stack, for customize previewer props
*/ */
@ -45,6 +52,24 @@ const resolve = (path: string): string => require.resolve(path);
const RoutesPlugin = (api: IApi) => { const RoutesPlugin = (api: IApi) => {
const ssrCssFileName = `ssr-${Date.now()}.css`; const ssrCssFileName = `ssr-${Date.now()}.css`;
const writeCSSFile = (key: string, hashKey: string, cssString: string) => {
const fileName = `emotion-${key}.${getHash(hashKey)}.css`;
const filePath = path.join(api.paths.absOutputPath, fileName);
if (!fs.existsSync(filePath)) {
api.logger.event(chalk.grey(`write to: ${filePath}`));
fs.writeFileSync(filePath, cssString, 'utf8');
}
return fileName;
};
const addLinkStyle = (html: string, cssFile: string) => {
const prefix = api.userConfig.publicPath || api.config.publicPath;
return html.replace('</head>', `<link rel="stylesheet" href="${prefix + cssFile}"></head>`);
};
api.registerTechStack(() => new AntdReactTechStack()); api.registerTechStack(() => new AntdReactTechStack());
api.modifyRoutes((routes) => { api.modifyRoutes((routes) => {
@ -81,18 +106,36 @@ const RoutesPlugin = (api: IApi) => {
// FIXME: workaround to make emotion support react 18 pipeableStream // FIXME: workaround to make emotion support react 18 pipeableStream
// ref: https://github.com/emotion-js/emotion/issues/2800#issuecomment-1221296308 // ref: https://github.com/emotion-js/emotion/issues/2800#issuecomment-1221296308
.map((file) => { .map((file) => {
let styles = ''; // let styles = '';
//
// extract all emotion style tags from body // // extract all emotion style tags from body
file.content = file.content.replace(/<style data-emotion[\S\s]+?<\/style>/g, (s) => { // file.content = file.content.replace(/<style data-emotion[\S\s]+?<\/style>/g, (s) => {
styles += s; // styles += s;
//
return ''; // return '';
// });
//
// // insert emotion style tags to head
// file.content = file.content.replace('</head>', `${styles}</head>`);
const antdCache = (global as any).styleCache;
// 1. 提取 antd-style 样式
const styles = extractStaticStyle(file.content, { antdCache, includeAntd: false });
api.logger.event(`@@@@@@@@@@@style amount ${styles.length}`);
// 2. 提取每个样式到独立 css 文件
styles.forEach((result) => {
api.logger.event(
`${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);
file.content = addLinkStyle(file.content, cssFile);
}); });
// insert emotion style tags to head
file.content = file.content.replace('</head>', `${styles}</head>`);
return file; return file;
}), }),
); );

1
package.json

@ -211,6 +211,7 @@
"cheerio": "1.0.0-rc.12", "cheerio": "1.0.0-rc.12",
"circular-dependency-plugin": "^5.2.2", "circular-dependency-plugin": "^5.2.2",
"cross-env": "^7.0.0", "cross-env": "^7.0.0",
"crypto": "^1.0.1",
"dekko": "^0.2.1", "dekko": "^0.2.1",
"dumi": "^2.1.17", "dumi": "^2.1.17",
"duplicate-package-checker-webpack-plugin": "^3.0.0", "duplicate-package-checker-webpack-plugin": "^3.0.0",

Loading…
Cancel
Save