diff --git a/components/config-provider/__tests__/theme.test.ts b/components/config-provider/__tests__/theme.test.ts index ddadd4de1b..0fd4ea4468 100644 --- a/components/config-provider/__tests__/theme.test.ts +++ b/components/config-provider/__tests__/theme.test.ts @@ -1,7 +1,17 @@ import { kebabCase } from 'lodash'; +import canUseDom from 'rc-util/lib/Dom/canUseDom'; import ConfigProvider from '..'; +import { resetWarned } from '../../_util/devWarning'; + +let mockCanUseDom = true; + +jest.mock('rc-util/lib/Dom/canUseDom', () => () => mockCanUseDom); describe('ConfigProvider.Theme', () => { + beforeEach(() => { + mockCanUseDom = true; + }); + const colorList = ['primaryColor', 'successColor', 'warningColor', 'errorColor', 'infoColor']; colorList.forEach(colorName => { @@ -22,4 +32,21 @@ describe('ConfigProvider.Theme', () => { expect(themeStyle.innerHTML).toContain(`--bamboo-${kebabCase(colorName)}: rgb(0, 0, 255)`); }); }); + + it('warning for SSR', () => { + resetWarned(); + + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); + mockCanUseDom = false; + expect(canUseDom()).toBeFalsy(); + + ConfigProvider.config({ + theme: {}, + }); + + expect(errorSpy).toHaveBeenCalledWith( + 'Warning: [antd: ConfigProvider] SSR do not support dynamic theme with css variables.', + ); + errorSpy.mockRestore(); + }); }); diff --git a/components/config-provider/cssVariables.tsx b/components/config-provider/cssVariables.tsx index 96f3dde0a8..e3b3c0c2cb 100644 --- a/components/config-provider/cssVariables.tsx +++ b/components/config-provider/cssVariables.tsx @@ -1,9 +1,11 @@ /* eslint-disable import/prefer-default-export, prefer-destructuring */ import { updateCSS } from 'rc-util/lib/Dom/dynamicCSS'; +import canUseDom from 'rc-util/lib/Dom/canUseDom'; import { TinyColor } from '@ctrl/tinycolor'; import { generate } from '@ant-design/colors'; import { Theme } from './context'; +import devWarning from '../_util/devWarning'; const dynamicStyleMark = `-ant-${Date.now()}-${Math.random()}`; @@ -86,12 +88,16 @@ export function registerTheme(globalPrefixCls: string, theme: Theme) { key => `--${globalPrefixCls}-${key}: ${variables[key]};`, ); - updateCSS( - ` + if (canUseDom()) { + updateCSS( + ` :root { ${cssList.join('\n')} } `, - `${dynamicStyleMark}-dynamic-theme`, - ); + `${dynamicStyleMark}-dynamic-theme`, + ); + } else { + devWarning(false, 'ConfigProvider', 'SSR do not support dynamic theme with css variables.'); + } }