TypeScript react frame component에 Emotion 적용하기 - boostcamp-2020/Project15-C-Client-Based-Formula-Editor GitHub Wiki

우리 팀은 리액트로 크롬, 웨일 확장프로그램을 만드는 작업을 하고 있다. 크롬 익스텐션을 popup 형태 말고 html 안에 넣기 위해선 iframe 형태로 새로운 html로 만들어서 넣어주어야했다. 그래서 찾은 라이브러리가 react-frame-component이다.

react-frame-component는 iframe으로 html 안에 또 다른 html을 삽입할 수 있게 도와주는 라이브러리이다. 그런데 여기에 기존처럼 emotion을 사용했을 때 css가 적용되지 않는 현상이 있었다.

여러가지 방식을 해보다가 겨우겨우 성공했다. 이런식으로 CacheProvider와 createCache를 사용하면 된다. 해당 사이트에서 도움을 받았는데 @emotion/core에서 CacheProvider를 가지고 오게 돼있는데 여기는 type이 정의되어있지 않아서 에러가 난다. @emotion/react는 type이 정의되어 있기 때문에 된다. @emotion/cache 또한 이미 type이 정의되어 있기 때문에 따로 @types 를 설치해주지 않아도 된다.

Emotion 문서

import * as React from 'react';
import Frame, { FrameContextConsumer } from 'react-frame-component';
import Content from './Content';
import { FormulaButton } from './Materials/Button';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';

const App = () => {
  return (
    <div id="my-extension">
      <FormulaButton onClick={() => console.log('test')}>체크</FormulaButton>
      <Frame
        head={[
 // css 파일로 넣으려면 여기에 넣으면 된다.
          <link type="text/css" rel="stylesheet" href={'content.css'}></link>,
        ]}
      >
        <FrameContextConsumer>
          {({ document }) => {
            const cache = createCache({  // createCache로 cache 생성
              key: 'head',
              container: document.head,
            });
            return (// CacheProvider 적용
              <CacheProvider value={cache}> 
                <Content />
              </CacheProvider>
            );
          }}
        </FrameContextConsumer>
      </Frame>
    </div>
  );
};

export default App;

Content안에 emotion 관련 부분은 원래대로 사용하면 된다.

⚠️ **GitHub.com Fallback** ⚠️