微前端开发时,使用cssinjs编写的组件打包后样式丢失

105 阅读1分钟

场景

  1. 在使用拆分公司的巨石项目时,往微前端方案迁移时,遇到了之应用保活出现的样式失效的问题

  2. 我测试了styled-components@emotion/reactantd-style都时一个结果

  3. 最后在一个大佬的启发下,发现这些cssinjs在生产环境做的优化导致,关闭这个优化就好了

解决方案

styled-components

import { StyleSheetManager } from 'styled-components';
function App() {
  return (
    <StyleSheetManager disableCSSOMInjection={true}>
      {/* 你的应用代码 */}
    </StyleSheetManager>
  );
}

@emotion/react

额外安装@emotion/cache

pnpm add @emotion/cache

import createCache from '@emotion/cache';
import { CacheProvider } from '@emotion/react';
const myCache = createCache({
  key: 'your-key', // 唯一 key 作为样式的前缀
  speedy: false, // 关闭快速插入方式
});
function App() {
  return (
    <CacheProvider value={myCache}>
      {/* 你的应用代码 */}
    </CacheProvider>
  );
}

antd-style

import { ConfigProvider } from 'antd';

function App() {
  return (
    <ConfigProvider autoInsertCSS={false}>
      {/* 你的应用代码 */}
    </ConfigProvider>
  );
}