Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tailwind v1.0 compatibility #20

Open
Shaderpixel opened this issue Mar 26, 2019 · 64 comments
Open

Tailwind v1.0 compatibility #20

Shaderpixel opened this issue Mar 26, 2019 · 64 comments
Labels
Projects

Comments

@Shaderpixel
Copy link

@Shaderpixel Shaderpixel commented Mar 26, 2019

Hi @bradlc, great work on creating this babel plugin. I am building my website using Gatsby and following the starter demo for Gatsby + Emotion + Tailwind (https://github.com/jlengstorf/gatsby-tailwind-demo). It works great with Tailwind v0.7.4.

I was poking around Tailwind site and noticed that Adam is planning a release of v1.0 soon and there are some changes in the way the config files are setup (especially in the theme area). I tried to use the beta v3 release with your plugin and run into an issue when I try to call the new color classes e.g. bg-gray-300 I get a TypeError: Cannot read property 'gray-300' of undefined. I am guessing this is related to how the config file structure has changed. I could be wrong but would love your input on this. Thanks.

@davecalnan
Copy link

@davecalnan davecalnan commented Apr 1, 2019

Hi @Shaderpixel, I ran into the same issue and looked into what would be required for Tailwind 1.0 capability. Unfortunately it doesn't seem to be a trivial update.

My exploration into the source code of this package and tailwindcss

Because pre-1.0 installations have the entire config explicitly listed in the tailwind.js file, it's relatively straightforward to pull in that config and figure out all of the generated classes. (It seems a whole other thing to parse all of the CSS-in-JS and replace the classes with the correct styles).

However with new 1.0 configs, there is new work involved in taking the (likely) minimal tailwind.config.js file and merging it with the default Tailwind config.

The default config has several keys that get a theme function which is called within postcss when building the Tailwind classes.

All this is to say that the work involved to get the resultant config has gone from importing your tailwind.js config file to importing the new tailwind.config.js file, merging it with the default config, and then running all of the functions that get the theme passed to it.

I'm going to try and update to support Tailwind 1.0

I love this package and would love to continue using it with Tailwind 1.*. I'm going to fork the package and get it 1.0 compatible and then create a pull request with the updates. @bradlc if you think that would be helpful, I would really appreciate your input! Thanks.

@bradlc bradlc added this to To do in v1 Apr 1, 2019
@bradlc bradlc added the v1 label Apr 1, 2019
@bradlc bradlc moved this from To do to In progress in v1 Apr 2, 2019
@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 2, 2019

Hey @Shaderpixel and @davecalnan

v1 support is very nearly done on the next branch. The main thing left to do is to update the static styles. I will try to publish it to npm this week under the next tag.

@DevanB
Copy link

@DevanB DevanB commented Apr 3, 2019

@bradlc I, too, am curious about 1.0. Great work updating this! I'm curious to try it out once you release it to the next tag!

bradlc added a commit that referenced this issue Apr 3, 2019
@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 3, 2019

Still got a bit to do but here's an initial version for anyone wanting to try it out 🎉 https://github.com/bradlc/babel-plugin-tailwind-components/releases/tag/v1.0.0-alpha.2

@Shaderpixel
Copy link
Author

@Shaderpixel Shaderpixel commented Apr 4, 2019

Awesome @bradlc, thanks for working so quickly on it. I will give it a whirl hopefully this weekend.

@pradel
Copy link

@pradel pradel commented Apr 5, 2019

I tried and for now it works well!
Thank you so much @bradlc 🙏
I tried to make it work with styled-components but no luck, I couldn't find how to make the custom config work.

@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 5, 2019

@pradel the config goes in a babel-plugin-macros config file. For styled-components you would want:

module.exports = {
  tailwind: {
    styled: 'styled-components'
  }
}

Is that what you have?

@pradel
Copy link

@pradel pradel commented Apr 5, 2019

@bradlc my bad, I was trying to set the config in .babelrc 🤦‍♂️ it's working now, thank you!

@Shaderpixel
Copy link
Author

@Shaderpixel Shaderpixel commented Apr 8, 2019

Hey @bradlc, I installed the tailwind.macro and using it with Gatsby. Here are my steps, please let me know if I am doing something wrong: I imported the macro into the document that I am working on and instead of using styled from @emotion/styled I will just use the tw tagged templates?

One more question, is the following no longer doable or I am just doing it wrong. Any suggestions how to accomplish something like the following?

const Paragraph = tw.p`
  flex justify-center items-center bg-gray-500
  color: ${props => (props.primary ? 'hotpink' : 'turquoise')};
`;

@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 8, 2019

Hey @Shaderpixel

Yeah so instead of this (which still works):

import styled from '@emotion/styled'
import tw from 'tailwind.macro'

const Paragraph = styled.p`
  ${tw`flex justify-center items-center bg-gray-500`}
`;

...you can do this:

import tw from 'tailwind.macro'

const Paragraph = tw.p`flex justify-center items-center bg-gray-500`;

Interpolations like in your example are not supported right now. You would have to do something like:

import styled from '@emotion/styled'
import tw from 'tailwind.macro'

const Paragraph = styled.p`
  ${tw`flex justify-center items-center bg-gray-500`}
  color: ${props => (props.primary ? 'hotpink' : 'turquoise')};
`;

In #22 I have an example of what I'd like to support with regards to interpolations. This would allow:

const Paragraph = tw.p`
  flex justify-center items-center bg-gray-500
  ${props => (props.primary ? { color: 'hotpink' } : { color: 'turquoise' })};
`;

Or if you have those colors in your Tailwind config:

const Paragraph = tw.p`
  flex justify-center items-center bg-gray-500
  ${props => (props.primary ? tw`text-hotpink` : tw`text-turquoise`)};
`;

Are you having trouble getting it to work at all right now?

@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 8, 2019

I have put together a PR for @jlengstorf's Gatsby demo which uses the alpha release: jlengstorf/gatsby-tailwind-demo#8

@Shaderpixel
Copy link
Author

@Shaderpixel Shaderpixel commented Apr 8, 2019

Sweet! Thanks for all the examples and ultra fast response. My issue was I was testing with the old configuration inside of gatsby-node.js that uses the Babel plugin but with the new tailwind.config.js and it obviously error out 🤦‍♂️ . But the interpolation now works well and I am looking forward to using the new interpolation methods in the future. Thanks for all your hard work. Should I close this issue now since support for v1.0 is almost done or you can close it with your v1.0 release?

@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 8, 2019

No problem! Let me know if you run into any other issues, or have any questions/suggestions.

Let's leave this open until it's released properly :)

@ockam
Copy link

@ockam ockam commented Apr 8, 2019

@bradlc I’m a bit confused by your gatsby-tailwind-demo PR, i.e. you are not using babel-plugin-macros in the packages. Is it required or not?

@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 8, 2019

@ockam
Copy link

@ockam ockam commented Apr 8, 2019

OK. When using the following code, I get the proper html node but css class do not work (I’m using Emotion):

import tw from "tailwind.macro"
const Test = tw.p` bg-pink text-red`

I don’t see any special config in the example. What am I missing?

@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 8, 2019

Are you using the default Tailwind v1 config (or no config)? If you are there is no bg-pink or text-red. Maybe try bg-pink-500 or text-red-500

@ockam
Copy link

@ockam ockam commented Apr 8, 2019

🤦‍♂️ too used to the old Tailwind syntax. Works fine now! Huge thanks for the quick reply!

@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 8, 2019

Hah no worries, I do the same thing when testing Tailwind v1 stuff. bg-red was my go-to test class 😅

We should probably throw an error when a class name is unrecognised. Currently unknown class names are just ignored.

@tobeycodes
Copy link

@tobeycodes tobeycodes commented Apr 13, 2019

My workaround for the above is. I did not want to hardcode the color so grab it from the config.

import tailwindConfig from '../tailwind.config';

const HeadingInner = styled.h1`
  ${tw`text-5xl font-light tracking-wider uppercase mb-6`}
  color: ${props => (props.dark ? tailwindConfig.theme.colors.gray['600'] : tailwindConfig.theme.colors.primary)}; 
`;

@DevanB
Copy link

@DevanB DevanB commented Apr 27, 2019

... the config goes in a babel-plugin-macros config file. For styled-components you would want:

module.exports = {
  tailwind: {
    styled: 'styled-components'
  }
}

Would it be possible to specify styled-components/macro in the future @bradlc? This would allow us to receive the beautiful babel-plugin-styled-components goodies like displayName?

The current work-around for this is:

const Wrapper = styled.div`
  ${tw`flex flex-col justify-between`}
`;

as opposed to

const Wrapper = tw.div`flex flex-col justify-between`;

@bradlc
Copy link
Owner

@bradlc bradlc commented Apr 28, 2019

@DevanB I’ve looked into this and there’s actually a bug in babel-plugin-styled-components that prevents it from working with tailwind.macro. The Tailwind macro produces code that looks like this:

import _styled from 'styled-components'

const Wrapper = _styled("div")({
  display: "flex",
  flexDirection: "column",
  justifyContent: "space-between"
});

babel-plugin-styled-components fails to transform code that looks like this, despite that fact that it is a valid way to create a styled component.

I think we can solve this on our end by updating how the macro transforms the code:

import _styled from 'styled-components'

- const Wrapper = _styled("div")({
+ const Wrapper = _styled.div({
  display: "flex",
  flexDirection: "column",
  justifyContent: "space-between"
});

@bradlc
Copy link
Owner

@bradlc bradlc commented May 5, 2019

@DevanB I’ve just published an update (v1.0.0-alpha.3) that will hopefully fix the issues with the styled-components babel plugin: npm install tailwind.macro@next

I think you might need to have babel-plugin-macros before babel-plugin-styled-components in your babel config. Let me know if that works ok for you.

@DevanB
Copy link

@DevanB DevanB commented May 5, 2019

@bradlc Updated, tested, and seem to see no differences. However, I am using CRA, so didn't specify babel-plugin-macros before babel-plugin-styled-components, because I'm not overriding the .babelrc, yet.

When I create with const Actionbar = styled.div`${tw`flex`}`;, I get:

const Actionbar = styled_components__WEBPACK_IMPORTED_MODULE_1__["default"].div.withConfig({
  displayName: "App__Actionbar",
  componentId: "sc-1m9o99g-2"
})(["", ""], {
  "display": "flex"
});

But when I create with const Actionbar = tw.div`flex`;, I get:

const Actionbar = styled_components__WEBPACK_IMPORTED_MODULE_1__["default"].div({
  "display": "flex"
}, p => p.tw);

It's quite possible that I need to override the .babelrc.

@apolzon
Copy link

@apolzon apolzon commented May 27, 2019

I'm still getting the same output as before. My hunch is that it has to do with the babel-plugin-macros.config.js file.

Here's the contents of my config file (located at my client root, its definitely getting read as my server will bomb if I replace '@emotion/styled/macro' with a typo):

module.exports = {
  tailwind: {
    styled: '@emotion/styled/macro'
  }
}

(also tried without the /macro suffix)

and here's a snippet from my test page:

import tw from 'tailwind.macro'
import styled from '@emotion/styled/macro'

...

const TailwindHeading = styled.h2`
  ${tw`text-indigo-600`};
`

const NewSyntax = tw.h2`
  text-indigo-600
`

...

<TailwindHeading>
  Tailwind + Emotion Test
</TailwindHeading>
<NewSyntax>
  New Syntax Test
</NewSyntax>

And here's what I see in the chrome inspector -- the TailwindHeading styles link to my source code (index.js), while the NewSyntax element is referencing the <style> element directly. (I've also tested with the css object style, and that works as well, but I omitted it from this example to try to reduce noise)

Screen Shot 2019-05-27 at 3 19 41 PM

Screen Shot 2019-05-27 at 3 19 52 PM

And here is the raw babel output for the two different styled syntaxes (notice the TailwindHeading element has the additional sourceMappingURL defined, while the NewSyntax element does not):

  var TailwindHeading = Object(_emotion_styled_base__WEBPACK_IMPORTED_MODULE_3__["default"])("h2", {
    target: "evcvfon0",
    label: "TailwindHeading"
  })(Object.assign(tailwind_macro_utils_umd_js__WEBPACK_IMPORTED_MODULE_4___default.a.resolveStyle(_tailwindConfig, [{
    "prop": "color",
    "config": "textColor"
  }, {
    "prop": "fontSize",
    "config": "fontSize"
  }], "indigo-600")), ";" + ( false ? undefined : "/*# sourceMappingURL=**omitted** */"));

  var NewSyntax = Object(_emotion_styled_base__WEBPACK_IMPORTED_MODULE_3__["default"])("h2", {
    target: "evcvfon1",
    label: "NewSyntax"
  })(Object.assign(tailwind_macro_utils_umd_js__WEBPACK_IMPORTED_MODULE_4___default.a.resolveStyle(_tailwindConfig, [{
    "prop": "color",
    "config": "textColor"
  }, {
    "prop": "fontSize",
    "config": "fontSize"
  }], "indigo-600")));

  return react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_5___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(TailwindHeading, {
    __source: {
      fileName: _jsxFileName,
      lineNumber: 54
    },
    __self: this
  }, "Tailwind + Emotion Test"), react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(NewSyntax, {
    __source: {
      fileName: _jsxFileName,
      lineNumber: 57
    },
    __self: this
  }, "New Syntax Test"));

I also did a test where I removed the styled.h2`` (TailwindHeading) element and styled import, with the same results -- the returned fragment has the __source key, but the initial creation of the element does not have the sourceMappingURL comment.

One last thing that has me puzzled is that the other syntaxes sourcemaps are working fine regardless of whether I define the babel-plugin-macros.config.js file. I'm not sure if this is due to some defaults working out of the box, or if there is something incorrect with my config which is the root issue.

@ockam
Copy link

@ockam ockam commented Jun 9, 2019

@bradlc using alpha.10 with Emotion in Gatsby, everything works fine with my components, but when I build my site, Tailwind defautConfig.stub.js gets lumped into the bundle. SInce it contains ES6 spread operator, this make older browsers crash (Edge, Explorer).

I tried building a simple test case with a new vanilla Gatsby and I don’t have this problem, so, it’s probably not an issue with the macro, but If you have a suggestion on what may cause this in my project, I’m out of idea to try...

@tobeycodes
Copy link

@tobeycodes tobeycodes commented Jun 16, 2019

I am now getting this error tailwind.macro: Cannot read property 'type' of undefined when using any class that uses a color e.g. text-red-500, bg-red-900. Other things work like underscore, p-10, m-10, etc. I'm using the following versions if it matters

    "styled-components": "^4.3.1",
    "babel-plugin-macros": "^2.6.1",
    "tailwind.macro": "^1.0.0-alpha.10",
    "tailwindcss": "^1.0.4"

EDIT: I do not get this anymore after nuking it and starting again.

@ynnoj
Copy link

@ynnoj ynnoj commented Jun 24, 2019

Anybody using this with Next.js/SSR?

@B3Kay
Copy link

@B3Kay B3Kay commented Jul 9, 2019

I can't get it to work with my tailwind.config.js. I can run it without it. Quite hard to grasp.

@cuong-nguyen
Copy link

@cuong-nguyen cuong-nguyen commented Aug 4, 2019

Hi, it seems like I can't do conditional like below

<span css={tw`text-xs flex items-center ${true ? 'uppercase' : ''}`}>

Is there a way I can make it dynamic like that? Thanks.

@tobeycodes
Copy link

@tobeycodes tobeycodes commented Aug 6, 2019

The type error I mentioned above is back :(

Works fine for anything like p-10 but colors do not work e.g. bg-red-500

./src/components/Button.js: ./src/components/Button.js: tailwind.macro: Cannot read property 'type' of undefined Learn more: https://www.npmjs.com/package/tailwind.macro
  
at assignify (./node_modules/tailwind.macro/macro.js:989:14)
at ./node_modules/tailwind.macro/macro.js:1004:24
at Array.forEach (<anonymous>)
  at assignify (./node_modules/tailwind.macro/macro.js:993:21)
  at getStyles (./node_modules/tailwind.macro/macro.js:1125:11)
  at ./node_modules/tailwind.macro/macro.js:1208:38
  at Array.forEach (<anonymous>)
    at babelPluginMacros.createMacro.configName (./node_modules/tailwind.macro/macro.js:1198:22)
    at macroWrapper (./node_modules/babel-plugin-macros/dist/index.js:61:12)
    at applyMacros **(./node_modules/babel-plugin-macros/dist/index.js:224:14)**

@tobeycodes
Copy link

@tobeycodes tobeycodes commented Aug 6, 2019

@bradlc Looks like the error goes away (and colors work) when I comment out this line. Do you have an idea of why this might be happening? Thanks again.

https://github.com/bradlc/babel-plugin-tailwind-components/blob/next/src/getStyles.js#L138

@cuong-nguyen
Copy link

@cuong-nguyen cuong-nguyen commented Aug 17, 2019

@bradlc I am on ^1.0.0-alpha.2.
Does it support custom plugin for tailwind? I tried adding sample plugin from https://tailwindcss.com/docs/adding-new-utilities#using-a-plugin but the styles are not available

Extend existing utility seems to work fine

module.exports = {
  theme: {
    extend: {
      inset: {
        '4': '1rem',
      },
    },
  },
  variants: {},
  plugins: [
     function({ addUtilities }) {
      const newUtilities = {
        '.rotate-0': {
          transform: 'rotate(0deg)',
        },
        '.rotate-90': {
          transform: 'rotate(90deg)',
        },
        '.rotate-180': {
          transform: 'rotate(180deg)',
        },
        '.rotate-270': {
          transform: 'rotate(270deg)',
        },
      }

      addUtilities(newUtilities, ['responsive', 'hover'])
    }
  ],
}

rotate- utilities are not there.

@tobeycodes
Copy link

@tobeycodes tobeycodes commented Aug 17, 2019

@cuong-nguyen
Copy link

@cuong-nguyen cuong-nguyen commented Aug 18, 2019

@schrapel good to know. Spent quite some time to make this macro works properly then hit this limitation. I think I will go for className approach then.

@alejandrovasta
Copy link

@alejandrovasta alejandrovasta commented Oct 19, 2019

Hey guys! could you make it work? I have no luck with Gatsby + Tailwind v1.0 and macro :( it runs on dev but when I try to build it does not happen

@flogy
Copy link

@flogy flogy commented Nov 4, 2019

Hey guys! could you make it work? I have no luck with Gatsby + Tailwind v1.0 and macro :( it runs on dev but when I try to build it does not happen

Hi @alejandrovasta

I too could not make it work for a long time. Then I discovered this awesome Gatsby theme: gatsby-theme-tailwindcss 😊

It supports Tailwind 1.x and also works when built (just tried it locally).

Side note: the theme also uses tailwind.macro etc. internally, so it does not support custom-forms at the moment.

Hope this helps!

@alejandrovasta
Copy link

@alejandrovasta alejandrovasta commented Nov 4, 2019

Puff awesome! it works. Thanks so much

@zamson
Copy link

@zamson zamson commented Nov 15, 2019

Wow this is so much cleaner than using className. So, will tailwind plugins just not work? That's a bummer. The custom-forms plugin is important to me. Are there any plans to make this work?

@leonardoelias
Copy link

@leonardoelias leonardoelias commented Nov 15, 2019

Wooow, this fantastic.

Any examples using next.js?

@tgrecojs
Copy link

@tgrecojs tgrecojs commented Nov 22, 2019

@leonardoelias the next.js examples repository has one that incorporates tailwind with emotion-js. not sure if you already came across that, but if not here it is: next.js examples - withtailwindcss-emotion 😎👍

@tobeycodes
Copy link

@tobeycodes tobeycodes commented Nov 22, 2019

I was using this with Next.js but now I pulled it out and just use className. Unfortunately I kept running into issues with this repo. I want to spend some time soon to try fix the issues I identified and add full tailwind v1 compatability

@deadcoder0904
Copy link

@deadcoder0904 deadcoder0904 commented Nov 22, 2019

@schrapel same. a project like this is better in the main repo where it gets maintained with recent changes or else we won't be able to enjoy new features :)

@tobeycodes
Copy link

@tobeycodes tobeycodes commented Nov 22, 2019

I don't think it will ever go into the main repo. I don't think it is something @admwathan would want.

I hope that @bradlc will find some time to review the PRs I will add but I understand that OSS is hard and we don't always have as much time to devote as we would like.

@noliiva
Copy link

@noliiva noliiva commented Dec 8, 2019

Hello there.
I'm pretty new to tailwindcss and I try to use it with the macro (alpha-10).
Base styles works fine but I can't use "container" class. I get this error: Error: Couldn’t resolve Tailwind class name: container.
I try to addComponent in config file to replace "container", but this didn't work.
Did I miss something ?

@tobeycodes
Copy link

@tobeycodes tobeycodes commented Dec 8, 2019

@noliiva the container class is not supported. You should use className for that

@noliiva
Copy link

@noliiva noliiva commented Dec 8, 2019

Oh, ok. That's sad. :p
Are there any plans to support this feature someday?

@mergims
Copy link

@mergims mergims commented Dec 12, 2019

@noliiva just had the same problem. I changed macro.js on row 1108 and it worked.

From:
var obj$1 = state.isProd ? resolveStyleFromPlugins(state.default, className) : ( obj$3 = {}, obj$3['__spread__' + index] = state.tailwindUtilsIdentifier.name + '.resolveStyleFromPlugins(' + state.tailwindConfigIdentifier.name + ', "' + className + '")', obj$3 );

To:
var obj$1 = state.isProd ? resolveStyleFromPlugins(state.config.default, className) : ( obj$3 = {}, obj$3['__spread__' + index] = state.tailwindUtilsIdentifier.name + '.resolveStyleFromPlugins(' + state.tailwindConfigIdentifier.name + ', "' + className + '")', obj$3 );

Basically, just change the config reference from state.default to state.config.default in the resolveStyleFromPlugins function call.

@noliiva
Copy link

@noliiva noliiva commented Dec 12, 2019

Oh, that's interesting !
Perhaps this should be added officially to the macro. :)

@mergims
Copy link

@mergims mergims commented Dec 12, 2019

@noliiva Yep. An option would be to fork the next branch and implement the fix if you need it urgently. And then add the git repo as a dependency in your project.

@tobeycodes
Copy link

@tobeycodes tobeycodes commented Dec 24, 2019

This might be useful. In a new project we decided to not use this package. Instead we load the Tailwind CSS file (purgecss/cssnano in production) and use a classnames function to choose the classes. It offers a similar developer experience. With Tailwind css v2 just around the corner this package we chose not to rely on this package for the time being.

Hope this helps someone

https://github.com/JedWatson/classnames

// Button.tsx
const Button: FC<ButtonProps> = ({ children, className, variant, size }: ButtonProps) => (
  <button
    className={classNames({
      'font-bold text-white': true,
      // Variants
      'border border-white': !variant,
      'bg-orange-500': variant === 'primary',
      'bg-gradient-brand': variant === 'secondary',
      // Sizes
      'px-5 rounded-3xl h-10': !size,
      'px-4 h-8 text-xs rounded-2xl md:px-5 md:text-base md:rounded-3xl md:h-10': size === 'small'
    })}
  >
    {children}
  </button>
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
v1
  
In progress
Linked pull requests

Successfully merging a pull request may close this issue.

None yet