/* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable no-param-reassign */ import fs from 'fs'; import path from 'path'; import { createHash } from 'crypto'; import createEmotionServer from '@emotion/server/create-instance'; import { cache } from '@emotion/css'; import type { IApi } from 'dumi'; function extractEmotionStyle(html: string) { if (html === undefined) { throw new Error('Did you forget to return html from renderToString?'); } const { extractCritical } = createEmotionServer(cache); const { ids, css } = extractCritical(html); if (!css) return []; return [ { key: cache.key, ids, css, tag: `` } ]; } export const getHash = (str: string, length = 8) => createHash('md5').update(str).digest('hex').slice(0, length); const dumiThemeUmiPlugin = (api: IApi) => { const writeCSSFile = (key: string, hashKey: string, cssString: string) => { const fileName = `style-${key}.${getHash(hashKey)}.css`; const filePath = path.join(api.paths.absOutputPath, fileName); if (!fs.existsSync(filePath)) { fs.writeFileSync(filePath, cssString, 'utf8'); } return fileName; }; const addLinkStyle = (html: string, cssFile: string, prepend = false) => { const prefix = api.userConfig.publicPath || api.config.publicPath; if (prepend) { return html.replace('', ``); } return html.replace('', ``); }; // add ssr css file to html api.modifyConfig((memo) => { // 将 .dumrc 中 ssr 配置注入 themeConfig 中,便于页面获取 memo.themeConfig.ssr = memo.ssr; return memo; }); api.modifyExportHTMLFiles((files) => { if (api.config?.ssr) { const nextFiles = files // exclude dynamic route path, to avoid deploy failed by `:id` directory .filter((f) => !f.path.includes(':')) .map((file) => { let globalStyles = ''; // Debug for file content: uncomment this if need check raw out // const tmpFileName = `_${file.path.replace(/\//g, '-')}`; // const tmpFilePath = path.join(api.paths.absOutputPath, tmpFileName); // fs.writeFileSync(tmpFilePath, file.content, 'utf8'); // extract all emotion style tags from body file.content = file.content.replace( /