Emotion은 styled-components와 비슷하게 emotion 컴포넌트를 CSS 선택자로 사용할 수 있습니다.
단, @emotion/babel-plugin 바벨 플러그인이 필요합니다.
import styled from '@emotion/styled'
const Child = styled.div`
color: red;
`
const Parent = styled.div`
// Parent 컴포넌트 내의 Child 컴포넌트의 글꼴 색은 green으로 나타납니다.
${Child} {
color: green;
}
`
return(
<div>
<Parent>
<Child>Green because I am inside a Parent</Child>
</Parent>
<Child>Red because I am not inside a Parent</Child>
</div>
)
Next.js 프로젝트의 경우 @emotion/babel-plugin
을 설치할 필요없이 next.config.js
에 compiler
속성을 다음과 같이 설정해주면 됩니다.
const nextConfig = {
...
compiler: {
// emotion 관련 옵션들을 기본값으로 설정
emotion: true
},
};
module.exports = nextConfig;
Next.js 12 버전부터 컴파일러를 기존 Babel에서 Rust 기반의 SWC로 변경하였습니다. 따라서, @emotion/babel-plugin
을 대신하여 SWC 컴파일러를 사용할 수 있습니다.
next.config.js
다음과 같이 emition을 설정할 수 있습니다.
module.exports = {
compiler: {
emotion: boolean | {
// default is true. It will be disabled when build type is production.
sourceMap?: boolean,
// default is 'dev-only'.
autoLabel?: 'never' | 'dev-only' | 'always',
// default is '[local]'.
// Allowed values: `[local]` `[filename]` and `[dirname]`
// This option only works when autoLabel is set to 'dev-only' or 'always'.
// It allows you to define the format of the resulting label.
// The format is defined via string where variable parts are enclosed in square brackets [].
// For example labelFormat: "my-classname--[local]", where [local] will be replaced with the name of the variable the result is assigned to.
labelFormat?: string,
// default is undefined.
// This option allows you to tell the compiler what imports it should
// look at to determine what it should transform so if you re-export
// Emotion's exports, you can still use transforms.
importMap?: {
[packageName: string]: {
[exportName: string]: {
canonicalImport?: [string, string],
styledBaseImport?: [string, string],
}
}
},
},
},
}
참고