4
votes

Can I use the styled components babel plugin in a create-react-app application that uses TypeScript?

I have read in the docs that there is a "macro [that] incorporates all the functionality of [the] babel plugin while allowing the unejected tooling to handle the Babel part of the build process."

I have tried:

npm install babel-plugin-macros

and

import styled from 'styled-components/macro';
const Div = styled.div`
`;

On npm run start in the console I get

Compiled with warnings.

./node_modules/babel-plugin-macros/dist/index.js
62:46-53 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

./node_modules/babel-plugin-macros/node_modules/cosmiconfig/dist/loaders.js
8:17-34 Critical dependency: the request of a dependency is an expression

When visiting the application in the browser I get

TypeError: __WEBPACK_IMPORTED_MODULE_1_styled_components_macro__.a.div is not a function
1
Did you manage to fix this? - Ashley Williams
I did not manage to fix this - user1283776

1 Answers

0
votes

I hit this same issue. I was trying to run a tsc -b -w (watch) over a monorepo while at the same time running a react-scripts start in a create-react-app project so I could watch projects and build upstream ones if they changed.

I eventually realized that the reason this wasn't working was because I had the styled components defined in a .ts file instead of a .tsx file, for example a Menu.styles.ts file. When I renamed it to Menu.styles.tsx the concurrent watch + start worked consistently.

Hope this helps someone.