Search code examples
typescriptcreate-react-appstyled-components

How to use styled components with babel plugin in create-react-app that uses TypeScript?


I have read the docs about styled components tooling. I have been able to use styled components without the babel plugin, but I have not been able to use style components with the babel plugin. From reading the docs, my impressions is that my best bet is to use the styled components macro.

My project uses

  • un-ejected create-react-app
  • TypeScript.

I have installed the following packages:

  "dependencies": {
    "styled-components": "^4.0.0"
  },
  "devDependencies": {
    "@types/styled-components": "^4.0.1",
    "babel-plugin-macros": "^2.4.2",
    "babel-plugin-styled-components": "^1.8.0"
  },

And here I use styled components in a .tsx file:

import styled from 'styled-components/macro';

Unfortunately I get this error:

[ts] Could not find a declaration file for module 'styled-components/macro'. '/Users/.../styled-components/dist/styled-components-macro.cjs.js' implicitly has an 'any' type.

I can get it to work by removing the /macro part of the import statement, but then I miss out on more readable class names during debugging as I understand it.


Solution

  • You can declare the styled-components/macro module as having API identical to styled-components by adding the following code to a .d.ts file in your project (not inside another module):

    declare module "styled-components/macro" {
        export * from "styled-components";
        import styled from "styled-components";
        export default styled;
    }
    

    Consider proposing this declaration in a pull request to DefinitelyTyped (in the proper format: there you'll need a separate macro.d.ts file instead of using declare module) and perhaps the @types/styled-components maintainers will know whether it is fully accurate.