Skip to content

Commit

Permalink
feat: antd first-screen style loading
Browse files Browse the repository at this point in the history
  • Loading branch information
2976151305 committed Jan 4, 2024
1 parent 35578ce commit 0cd1837
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 29 deletions.
36 changes: 36 additions & 0 deletions web/genAntdCss.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { createHash } from 'crypto';
import fs from 'fs';
import path from 'path';
import { extractStyle } from '@ant-design/cssinjs';
import type Entity from '@ant-design/cssinjs/lib/Cache';

export type DoExtraStyleOptions = {
cache: Entity;
dir?: string;
baseFileName?: string;
};
export function doExtraStyle({ cache, dir = 'antd-output', baseFileName = 'antd.min' }: DoExtraStyleOptions) {
const baseDir = path.resolve(__dirname, '../../static/css');

const outputCssPath = path.join(baseDir, dir);

if (!fs.existsSync(outputCssPath)) {
fs.mkdirSync(outputCssPath, { recursive: true });
}

const css = extractStyle(cache, true);
if (!css) return '';

const md5 = createHash('md5');
const hash = md5.update(css).digest('hex');
const fileName = `${baseFileName}.${hash.substring(0, 8)}.css`;
const fullpath = path.join(outputCssPath, fileName);

const res = `_next/static/css/${dir}/${fileName}`;

if (fs.existsSync(fullpath)) return res;

fs.writeFileSync(fullpath, css);

return res;
}
43 changes: 41 additions & 2 deletions web/pages/_document.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,45 @@
import Document, { Head, Html, Main, NextScript } from 'next/document';
import { createCache, StyleProvider } from '@ant-design/cssinjs';
import Document, { DocumentContext, Head, Html, Main, NextScript } from 'next/document';
import { doExtraStyle } from '../genAntdCss';

interface Props {
currentUrl: string;
}

class MyDocument extends Document<Props> {
static async getInitialProps(ctx: DocumentContext) {
const cache = createCache();
let fileName = '';
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
(
<StyleProvider cache={cache}>
<App {...props} />
</StyleProvider>
),
});
const initialProps = await Document.getInitialProps(ctx);
const currentUrl = ctx.req?.url;

fileName = doExtraStyle({
cache,
});

return {
...initialProps,
currentUrl,
styles: (
<>
{initialProps.styles}
{/* 1.2 inject css */}
{fileName && <link rel="stylesheet" href={`/${fileName}`} />}
</>
),
};
}

class MyDocument extends Document {
render() {
return (
<Html lang="en">
Expand Down
27 changes: 0 additions & 27 deletions web/pages/chat/[scene]/[id].tsx

This file was deleted.

0 comments on commit 0cd1837

Please sign in to comment.