emotion: Component selectors don't work with TypeScript `CreateStyled`
emotionversion: 10.0.10reactversion: 16.8.6
Relevant code:
styled.ts:
import styled, { CreateStyled } from '@emotion/styled'
import { Theme } from './theme'
export default styled as CreateStyled<Theme>
text.tsx:
import styled from 'src/styles/styled'
// ...
export const Title2 = styled<'h3', TextProps>('h3')`
color: ${props => props.theme.colors.charcoalGrey};
${typography.title2}
${textStyles}
`
export const SectionTitle = styled<'h4', TextProps>('h4')`
color: ${props => props.theme.colors.charcoalGrey};
${typography.sectionTitle}
${textStyles}
`
someOtherFile.tsx:
const DeduplicateExaggeratedMargins = styled(Box)`
${Title2} + ${SectionTitle} {
margin-top: ${props => props.theme.space[standardMargin]}px;
}
`
What you did:
- I followed the instructions here to define a theme with our own version of
styled. - Now I can’t use Component Selectors!
What happened:
I received an error:
Error: Component selectors can only be used in conjunction with babel-plugin-emotion.
Reproduction:
Problem description:
Switching to test.tsx to use import styled from '@emotion/styled' rather than our version of styled with theming.
Suggested solution:
Make babel-plugin-emotion support what is documented in the “Typescript.md” file.
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 11
- Comments: 16 (2 by maintainers)
I had the same problem with
CreateStyled<Theme>and i fixed it in a simple way (i think) taking the problem into the typings that is where the problem comes.I “overrode” the existing typings from @emotion/styled because it is the problem of our not typed theme in styled-components.
customTypings.d.ts
Whit this, you can use the @emotion/styled (this is the alias that you need to use because macros search this alias from babel-preset-emotion and if you use other it will no parse anything)
I am doing the same that you have to do to create a “custom theme” into typings, with this i avoid to play gith alias in webpack and declare this modules in typings (it creates problems with HMR).
When you use your styled now you have a typed theme.
anyComponent.tsx
There is only one case in which this solution doesn’t work, it is if you need to have more than one different theme in the same project (to be honest i don’t think anybody need this)
So no one else has to retype the above code, I added
types/@emotion/styled.d.tscontaining:I have the same problem… I switched to
import styled from "@emotion/styled"but its really pain in the a** to be without typedthemeproperty. Did maybe some managed to do some workaround for injecting theme interface…