ben-rogerson / twin.macro

🦹‍♂️ Twin blends the magic of Tailwind with the flexibility of css-in-js (emotion, styled-components, solid-styled-components, stitches and goober) at build time.
MIT License
7.92k stars 183 forks source link

Docs: `babel-plugin-styled-components` must be used with `babel-plugin-macros` #737

Closed finnmerlett closed 1 year ago

finnmerlett commented 2 years ago

It looks like it's necessary need to add "babel-plugin-macros" beforebabel-plugin-styled-components in the babel plugins array. I was trawling the web for ages trying to get babel-plugin-styled-components working for Twin in CRA. I was using CRACO to add babel plugins, but nothing I was doing was working.

I finally stumbled upon your absolutely perfect example repo twin.examples/webpack-styled-components-typescript which contained literally everything I wanted. Here is the .babelrc file:

{
  "presets": [
    [
      "@babel/preset-react",
      { "runtime": "automatic" }
    ],
    "@babel/preset-typescript"
  ],
  "plugins": [
    "babel-plugin-twin",
    "babel-plugin-macros",
    "babel-plugin-styled-components"
  ]
}

The plugins part was what I needed, so I just copied it across and everything worked perfectly.

To check applications to situations without babel-plugin-twin (and to answer this SO question), I removed it from the plugins list and tested my setup using the alternative method for using Twin (adding import "twin.macro" at the top of the file I was styling in). The setup worked, but not if I removed babel-plugins-macro.

What seems odd is CRA already loads babel-plugins-macro from babel-preset-react-app. I think actually babel-plugins-macro needs to be specifically loaded just before babel-plugin-styled-components, as I tried swapping the order of just those two and it silently broke the styling. It might be worth adding this to the documentation that mentions babel-preset-styled-components, to help out others struggling with the same issue.

ben-rogerson commented 2 years ago

Great to hear you found a solution.

I agree the docs should probably mention babel-plugin-macros needs to be added before babel-plugin-styled-components - feel free to send up a PR in the styled-components examples otherwise I'll add this to my todo list.

ben-rogerson commented 1 year ago

I've now added a note in the readme about this - cheers