Giter VIP home page Giter VIP logo

twin.examples's Introduction

Twin examples Twin examples

Packed with examples for different frameworks,
this repo helps you get started with twin.macro a whole lot faster.

Total Downloads Latest Release Discord


Examples

App build tools and libraries

Advanced frameworks

Component libraries

πŸŽ‰Β : Fresh example

Contributions

Contributions are welcome! Feel free to report any issues or add a new example to this list via a PR.

Community

Drop into our Discord server for announcements, help and styling chat.

Discord

twin.examples's People

Contributors

0n3byt3 avatar aleksa-codes avatar andreidobrinski avatar ben-rogerson avatar beshoi avatar chrismwilliams avatar clarencec avatar code-sanchu avatar codemonkey800 avatar delster avatar fatehwaharp avatar felipelube avatar giacomorebonato avatar jqkk avatar locona avatar pix2d avatar rottitime avatar rub1e avatar soilspoon avatar terrywmc avatar u3u avatar whatishedoing avatar zax-xyz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

twin.examples's Issues

Twin.macro emotion example flickering when build for production

  1. The buggy behavior you’re experiencing and what should be happening instead
    I tried this example https://github.com/ben-rogerson/twin.examples/tree/master/next-emotion
    but when I build & start (for production) then go to localhost:3000 and refresh page the UI seems flickering.
    It does not happen in the development mode.

2564-02-06 15-43-07 2564-02-06 15_43_20

After some debugging seems like calc css function not call on server-side
image
I guess

  1. If you're using styled-components, emotion, goober, or something else
    emotion

  2. A link to a minimal demo showing the bug in action
    fork this repo https://github.com/ben-rogerson/twin.examples/tree/master/next-emotion
    and use yarn build && yarn start

CSS files

Not really a bug, just a query, when I run Tailwind (with Styled Components) in my small NextJS project and run it on dev or buid -> start all the styles work perfectly.

However when I look in the .next folder I can't see any generated CSS files.

Where is the CSS?

Received `true` for a non-boolean attribute

In my Stitches - Twin.Macro implementation, I have a typical <Button /> component with a variant: big which is a boolean.

Nothing special here:

const StyledButton = styled.button({
  ...tw`overflow-hidden`,
  ...tw`bg-grayBase text-grayDark font-medium hocus:(outline-none ring-0)`,
  ...tw` px-4 py-2 rounded-full hover:(opacity-90)`,
  variants: {
    big: { true: tw`px-6 py-6 text-2xl text-grayBlack` },
...
const Button: React.FC<Props> = ({ children, loading, onClick, ...props }) => {
  return (
    <StyledButton {...props} onClick={onClick}>
...

But when I use it like <Button big (+ other props) /> I get this warning:

Warning: Received `true` for a non-boolean attribute `big`.
If you want to write it to the DOM, pass a string instead: big="true" or big={value.toString()}.

Any idea how to solve it?
Thanks.

Module not found: Can't resolve 'fs'

Overview

Hi, So I'm running a recently created NextJS App w/ Emotion + Tailwindcss and followed this guide: https://github.com/ben-rogerson/twin.examples/tree/master/next-emotion but it doesn't seem to work.

System Information:
Node: 16.0.0
Npm: 7.10.0

Here are the steps I took:

  1. Installed NextJS via create-next-app and migrated over to typescript.
  2. Ran npm install @emotion/react @emotion/styled @emotion/css @emotion/server which worked fine.
  3. Then I ran: npm install -D twin.macro tailwindcss @emotion/babel-plugin babel-plugin-macros which failed because of this error:
npm ERR! Found: [email protected]
npm ERR! node_modules/postcss
npm ERR!   postcss@"8.1.7" from [email protected]
npm ERR!   node_modules/next
npm ERR!     next@"10.1.3" from the root project
npm ERR!   peer postcss@"^8.0.9" from [email protected]
npm ERR!   node_modules/tailwindcss
npm ERR!     dev tailwindcss@"*" from the root project
npm ERR!     tailwindcss@"^2.0.1" from [email protected]
npm ERR!     node_modules/twin.macro
npm ERR!       dev twin.macro@"*" from the root project
npm ERR!   2 more (autoprefixer, postcss-js)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer postcss@"^8.1.13" from [email protected]
npm ERR! node_modules/tailwindcss/node_modules/postcss-nested
npm ERR!   postcss-nested@"5.0.5" from [email protected]
npm ERR!   node_modules/tailwindcss
npm ERR!     dev tailwindcss@"*" from the root project
npm ERR!     1 more (twin.macro)
npm ERR! 

so I figured that tailwind still needed postcss and it's config file. So I ran the following:

  1. npm install -D tailwindcss@latest postcss@latest autoprefixer@latest which resolved the post css fix.
  2. Then I reran the command in #2: npm install -D twin.macro tailwindcss @emotion/babel-plugin babel-plugin-macros and it worked perfectly.
  3. Then I edited my _app.js file to do this:
import { GlobalStyles } from 'twin.macro'

export default function MyApp({ Component, pageProps }) {
  return <><GlobalStyles /><Component {...pageProps} /></>
}
  1. Finally I did npm run dev and I'm getting the following issue:
error - ./node_modules/cosmiconfig/dist/readFile.js:9:0
Module not found: Can't resolve 'fs'
null
error - ./node_modules/cosmiconfig/dist/readFile.js:9:0
Module not found: Can't resolve 'fs'
null

Why is this occuring and also why does your instructions never include the postcss install portion as well as autoprefixer from tailwind's website.

[component-library-emotion] can't overwrite the config in components with the config in app

component-library-emotion

Currently, I can't overwrite the config(ex colors) set in components with the config set in app.

app/tailwind.config.js
components/tailwind.config.js

Do you know the best way to solve this problem?

From what I have found, defining the following on the components side may work.
I will test this in the future.

components/tailwind.config.js

module.exports = {
  theme: {
    colors: {
      red: {
        medium: '#e53e3e',
        dark: '#742a2a'
      },
      blue: {
        medium: '#3182ce',
        dark: '#2a4365'
      },
      'th-primary': 'var(--primary)',
      'th-secondary': 'var(--secondary)'
    }
  }
}

components/index.css

:root {
  --primary: theme('colors.red.dark');
  --secondary: theme('colors.red.medium');
}


.th-blue {
  --primary: theme('colors.blue.dark');
  --secondary: theme('colors.blue.medium');
}

Issues with Typescript examples of Emotion and styled-components

Following the guide here , I edited my tsconfig.json and added twin.d.ts in my root folder of the project.

Everything seems to work ( I can use styled when imported from twin.macro., and the components will render correctly. However, I'm still receiving these errors in vscode:

image

image

The tsconfig was created by tsc --init, and I added the files property after the fact (shown above)

FOUC

There's an example for fixing FOUC in next-styled-components.
Is there an example for next-emotion?
Thank you!

Server Stylesheet Question

I am trying to follow the instructions to add a server stylesheet as noted here: https://github.com/ben-rogerson/twin.examples/tree/master/next-styled-components#add-the-server-stylesheet

However, my pages/_document.js is set up slightly differently then in your example and I am having a hard time figuring out how to mere the two. Here is how my pages/_document.js file looks:

import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";

export default class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          // HEADER SCRIPTS
        </Head>
        <body>
          <noscript>
            // OTHER SCRIPTS
          </noscript>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

Any suggestion on how to add a Server Stylesheet to the above code?

Thanks.

Next.js + Emotion Example Causes FOUC

Using theCacheProvider with Next and Emotion causes the built site to not produce CSS files or inline CSS in the HTML output.

The fix is to remove the CacheProvider from _app.js entirely, which I discovered in this PR comment: vercel/next.js#17651 (comment). The built HTML for SSR / SSG pages now contains inlined CSS.

Not able to make twin work with Storybook

I have configured twin macro to work with nextjs and emotion. It works great!

However, when I try to add the component to Storybook I get the following error:

RROR in ./components/Apple.js
Module not found: Error: Can't resolve '@emotion/styled-base' in '/Users/antonkouliavtsev/Projects/clients/stoked/nucleus-tenant/web/client/components'
 @ ./components/Apple.js 1:0-44 17:12-20
 @ ./stories/Apple.stories.js
 @ ./stories sync ^\.(?:(?:^|\/|(?:(?:(?!(?:^|\/)\.).)*?)\/)(?!\.)(?=.)[^/]*?\.stories\.(js|jsx|ts|tsx))$
 @ ./.storybook/generated-stories-entry.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/storybook-init-framework-entry.js ./node_modules/@storybook/addon-docs/dist/frameworks/common/config.js-generated-other-entry.js ./node_modules/@storybook/addon-docs/dist/frameworks/react/config.js-generated-other-entry.js ./node_modules/@storybook/addon-links/dist/preset/addDecorator.js-generated-other-entry.js ./node_modules/@storybook/addon-actions/dist/preset/addDecorator.js-generated-other-entry.js ./node_modules/@storybook/addon-actions/dist/preset/addArgs.js-generated-other-entry.js ./node_modules/@storybook/addon-backgrounds/dist/preset/defaultParameters.js-generated-other-entry.js ./.storybook/preview.js-generated-config-entry.js ./.storybook/generated-stories-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=false&noInfo=undefined

I am a bit confused on how to get this configured, since setting emotion through twin macro is slightly different than doing the standalone setup.

Using <GlobalStyles /> with Next.js + styled-components outputs external .css file instead of inline css

Hey,

first of all thanks a lot for twin.macro!

I played around with using twin.macro in Next.js and found out that when using in _app.js and a production build (next build), those global styles (especially modern-normalize from tailwindcss/dist/base.min.css are extracted into a separate .css file.

As I would like to have all styles inlined in the SSR html response (as that's kind of the idea of css-in-js), is there a way to make that work with Next.js?

Here's the Next.js + styled-components example with a modified npm run dev in package.json to produce a production build: https://codesandbox.io/s/frosty-bush-hxl0h

Thanks!

Next.js styled-components & emotion examples do not work using Yarn 2

When using Yarn 2 Plug'n'Play and following the instructions exactly, for styled-components I get this error on running next dev:

error - ./.yarn/$$virtual/next-virtual-5d5df27552/0/cache/next-npm-10.0.4-e9908bac70-5ec6818d46.zip/node_modules/next/dist/client/next-dev.js
Error: Cannot find module '@emotion/babel-plugin' from 'e:\Documents\GitHub\repo'
    at Array.map (<anonymous>)
    at Generator.next (<anonymous>)
    at loadFileChain.next (<anonymous>)

As for emotion:

error - ./.yarn/$$virtual/next-virtual-5d5df27552/0/cache/next-npm-10.0.4-e9908bac70-5ec6818d46.zip/node_modules/next/dist/client/next-dev.js
Error: Cannot find module 'babel-plugin-macros' from 'e:\Documents\GitHub\repo'
    at Array.map (<anonymous>)
    at Generator.next (<anonymous>)
    at loadFileChain.next (<anonymous>)

I think it is likely an issue with Babel or Nextjs itself but I do not have the expertise to debug it. Works fine if I switch Yarn 2's nodeLinker to node-modules mode. So I am guessing likely a bad import somewhere.

Next-Emotion is not working.

info  - Using external babel configuration from /Users/vikash/Downloads/ben-rogerson twin.examples master next-emotion/.babelrc
error - ./node_modules/tailwindcss/dist/base.min.css
Error: No PostCSS Config found in: /Users/vikash/Downloads/ben-rogerson twin.examples master next-emotion/postcss.config.js

`tw` and `css` props don't work in stitches example

I've found that only styled-components made using the styled syntax from stitches are working. The tw and css props are not working at all. Here is the generated output.
2021-05-23_18-29

I use the latest versions for both stitches and twin.

Snowpack React Emotion: Error upon clean startup

Just to report a problem running one of the examples.
Tried with Node 12.20 and 14.15

What I did:

  • a fresh download of snowpack-react-emotion
  • Then yarn
  • Then yarn start

Results:

  • dependencies installed correctly without errors
  • server started well without errors in the console either
  • the page was served at http://localhost:8080
  • the page failed to render and showed an error: base.min.css.proxy.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "text/css". Strict MIME type checking is enforced for module scripts per HTML spec.

I did not install anything else or do any changes.

Searching Google didn't yield any tangible info so I share this here.

I also tried cra-emotion and that one worked fine!

Can't resolve 'tailwindcss/dist/base.min.css'

I have followed the Next-Emotion example Readme to update twin.macro v1.12.0 to v2.0.4.

I receive the following error when running the dev script:

error - ./pages/_app.js
Module not found: Can't resolve 'tailwindcss/dist/base.min.css' in 'X:\Programming\{....}\pages'

Current dependencies

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
 "dependencies": {
    "@emotion/babel-preset-css-prop": "^11.0.0",
    "@emotion/css": "^11.0.0",
    "@emotion/react": "11.0.0",
    "@emotion/styled": "^11.0.0",
    "next": "latest",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "twin.macro": "^2.0.4"
  },

When adding the tailwindcss package (like the Next-Emotion example) the app works.

This is currently not included in the Readme. I'm not sure if this is something that needs to be included or just a bug on my end.

Nextjs emotion global.css conflicting with GlobalStyle development

Attempting to use twailwind layers to customize the CSS, but it seems GlobalStyle in development the style get mounted AFTER the custom style. So it gets overridden.

@import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&display=swap');

@layer base {
  html {
    @apply font-sans;
  }

  h1 {
    @apply text-2xl;
    @apply font-bold;
  }
  h2 {
    @apply text-xl;
    @apply font-bold;
  }
  h3 {
    @apply text-lg;
    @apply font-bold;
  }
  h4 {
    font-size: 5rem;
  }
}

Below is the results

image

You can see the h4 is lower in specificity. In production when I build it, the sheets are correct it seems.

image

Curious if you had any ideas on work around OR if this something in GlobalStyle that needs fixed or I am doing something wrong?

Thanks

[next-stitches-typescript] `styled` is of type `any`

In the next-stitches-typescript example, the styled import from twin.macro is considered type any by typescript, so we lose intellisense here. Typing styled. doesn't bring up the possible attributes (e.g., a, button, div, ...), and attempting to use a non-existent property has no compile-time error (e.g., styled.asdf).

This is a result of improper type definitions in types/twin.d.ts, as typeof StyledTags gets evaluated to any, since StyledTags itself is already a type. Further, the | in styled's type definition should be a & to combine the properties (otherwise we get type errors after fixing the any issue, trying to access a property that's only on one of the possibilities, e.g., button.

next js example needs to update the globalStyles.tsx file

On the example, https://github.com/ben-rogerson/twin.examples/tree/master/next-stitches-typescript tells to create the styles/globalStyles.tsx and import global from ../stitches.config:

// styles/globalStyles.tsx
import { globalStyles } from 'twin.macro'
import { global } from '../stitches.config'

const styles = global(globalStyles)

export default styles

but, on ../stitches.config file example there is not any global to be imported:

// stitches.config.ts
import { createStitches, CSS as StitchesCSS } from '@stitches/react'
export type { CSS } from '@stitches/react/types/css-util'

export const stitches = createStitches({
  prefix: '',
  theme: {},
  utils: {},
})

export const { css, styled, globalCss, theme, keyframes, getCssText } = stitches

Suggested solution

update the example with same content of the file https://github.com/ben-rogerson/twin.examples/blob/master/next-stitches-typescript/styles/globalStyles.tsx

import { DefaultThemeMap } from '@stitches/react'

import tw, { theme, globalStyles } from 'twin.macro'
import { globalCss, CSS } from '../stitches.config'

const customStyles = {
  body: {
    WebkitTapHighlightColor: theme`colors.purple.500`,
    ...tw`antialiased`,
  },
}

const styles = () => {
  globalCss(customStyles)()
  globalCss(globalStyles as Record<any, any>)()
}

export default styles

Using the next example - styling `next/link` doesn't appear to work

I've used npx degit https://github.com/ben-rogerson/twin.examples/next-emotion folder-name and have not been able to style the Link imported from Next. Thinks I have tried include:

import tw from 'twin.macro'
import NextLink from 'next/link'

export const Link = tw(NextLink)`px-4 py-2 text-sm font-medium text-white`

import { styled } from 'twin.macro'
import NextLink from 'next/link'

export const Link = styled(NextLink)(() => [
  `px-4 py-2 text-sm font-medium text-white`
])

I have also tried using the css or tw props directly on the Link component.

Please let me know if I'm doing something wrong here, I'm new to this. Thanks!

[component-library-styled-components] issue with Storybook.

Hi there, just wanted to say amazing project! Loving using it so far. I used your component-library-styled-components with Next.js example and then added Storybook as you have in the storybook-styled-components-typescript example.

In my project, I extend tailwind's config to add custom colours e.g: base, primary, secondary, etc... My issue is that compiling the monorepo requires that a package must have the babelMacros inside it's respective package.json but when Storybook imports those packages they seem to conflict somehow and remove the custom tailwind config. Removing the babelMacros from the package.json for a package fixes the issue when you want to run Storybook, but then it will have to be re-added when you want to compile the project as a whole.

I was hoping you'd have some idea of why this may happen, as the error logs only say that the generated classes for the custom colours don't exist e.g: "bg-base-100 was not found. Did you mean bg-blue-100".

Cheers!

Style flickering occurring in Next.js app

I followed the Next.js + Emotion guide.

This is my _document file:

/* eslint-disable react/no-danger */
import React from "react";
import Document, {
  Html,
  Head,
  Main,
  NextScript,
  DocumentContext,
  DocumentInitialProps,
} from "next/document";
import { extractCritical } from "@emotion/server";

interface Props {
  css: string;
  ids: string[];
}
class CustomDocument extends Document<Props> {
  static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
    const initialProps = await Document.getInitialProps(ctx);
    const page = await ctx.renderPage();
    const styles = extractCritical(page.html);
    return { ...initialProps, ...page, ...styles };
  }

  render(): React.ReactElement {
    return (
      <Html lang="en">
        <Head>
          <link rel="shortcut icon" href="/favicon.svg" />
          <style
            data-emotion-css={this.props.ids.join(" ")}
            dangerouslySetInnerHTML={{ __html: this.props.css }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default CustomDocument;

And I added <GlobalStyles /> to my _app file.

This is my .babelrc.js:

module.exports = {
  presets: [
    [
      "next/babel",
      {
        "preset-react": {
          runtime: "automatic",
          importSource: "@emotion/react",
        },
      },
    ],
  ],
  plugins: [
    "@emotion/babel-plugin",
    "babel-plugin-macros",
    "@babel/plugin-proposal-export-namespace-from",
  ],
};

So it's all set up according to the instructions. There is no flickering in development, which is fine.

However, in production, _document isn't setting the critical Emotion styles. It has the <style> tag:

<style data-emotion-css=""></style>

But the styles are empty. I'm not sure why this is.

component-library-emotion: webpack5 not working

I am trying to use webpack5 for "component-library-emotion".

However, I am getting the following error.

Error Message

Error: Cannot find module 'components'

The only changes I made were.
ref: #50 (comment)

// next.config.js

module.exports = {
  future: {
    webpack5: true,
  },
  webpack: (config) => {
    config.resolve.fallback = {
      fs: false,
      module: false,
    }

    return config
  },
}

What other changes do you think are needed?

Group variants don't respect the conditionals within styled components

Using group variants within a condition of a styled component, makes any implementation of the styled component trigger on the group variant whether it satisfies the condition or not.

See this sandbox for a minimal replication. https://codesandbox.io/s/pedantic-driscoll-ux939?file=/src/App.js

I can see the reason for it happening is the group:hover selector is applied for the same class for both the boxes. Not sure if it's meant to be applied for the class cSHLIC instead of App__TestStyled-... as in the image below. I don't know much about how styled components work so this might be a silly suggestion πŸ˜„

image

In a project I'm working on, we replicate container queries in a similar method - attaching a class of sm, md etc to a container depending on it's width and using custom selectors sm:, md: to style based on whether they are a descendant of an element with that class. Which means we can't use these responsive selectors within a condition of a styled component.

Thanks for your help and let me know if I can explain more or help fix the issue.

Styled-components 'as' prop type fix

Dependencies:

 "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "@types/styled-components": "^5.1.9",
    "styled-components": "^5.2.1",
    "tailwindcss": "^2.0.2",
    "twin.macro": "^2.3.1",
    "typescript": "^4.1.3"
  },
  "devDependencies": {
    "@types/react": "^17.0.3",
    "@types/react-dom": "^17.0.3",
    "@babel/cli": "^7.13.10",
    "@babel/core": "^7.13.10",
    "@babel/preset-env": "^7.13.12",
    "@babel/preset-react": "^7.12.13",
    "@babel/preset-typescript": "^7.13.0",
    "babel-plugin-macros": "^3.0.1",
    "babel-plugin-twin": "^1.0.2"
  }

Sample component:

const Heading: React.FC<HeadingProps> = (props) => {
  const { variant, ...rest } = props

  return (
    <h1
      as={`h${variant}`}
      css={[
        tw`font-display font-bold`,
        [...]
      ]}
      {...rest}
    />
  )
}

With the provided twin.d.ts types in the styled-components cra example, I get the typescript error:
Property 'as' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>'.

However, moving the 'as' definition from the global scope to react fixes all errors.

twin.d.ts:

import 'twin.macro'
import styledImport, { CSSProp, css as cssImport } from 'styled-components'

declare module 'twin.macro' {
  // The styled and css imports
  const styled: typeof styledImport
  const css: typeof cssImport
}

declare module 'react' {
  // The css prop
  interface HTMLAttributes<T> extends DOMAttributes<T> {
    css?: CSSProp
    as?: string                    // πŸ‘ˆ added
  }
  // The inline svg css prop
  interface SVGProps<T> extends SVGProps<SVGSVGElement> {
    css?: CSSProp
  }
}

Typescript types for component selectors that use object syntax in emotion

The existing demo of twin.macro + vite + emotion does not appear to allow component selectors using object syntax, e.g. as in the following snippet:

const Child = styled.div({
  color: 'red',
})

const Parent = styled.div({
  [Child]: {
    color: 'green',
  },
})

In order to enable that feature I had to add @emotion/babel-plugin as a dev dependency and inside the babel plugin list in vite.config.ts. While that made component selectors work, the type definitions provided in the vite+emotion example still flagged the [Child]:{...} selector as invalid. You can see the behavior in this CS. Can this be corrected by expanding the types in twin.d.ts, similar to the suggestion in ben-rogerson/twin.macro#116?

One other notable aspect of such an addition -- the component selector can be arbitrarily deep inside the selector tree, e.g. {'&:hover': { [Child]: { color: 'green' }}}.

Cannot use with next-plugin-antd-less 3 21034

I started with the template with stitches and follow the install instructions from https://github.com/SolidZORO/next-plugin-antd-less. Is there a way to use two packages at the same time?

Error massage:
`Critical dependency: the request of a dependency is an expression

./node_modules/twin.macro/macro.js
Critical dependency: the request of a dependency is an expression

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

next.config.js
`const withAntdLess = require("next-plugin-antd-less");

module.exports = withAntdLess({
webpack(config) {
config.resolve.fallback = {
fs: false,
module: false,
path: false,
os: false,
};
return config;
},
});
`

babelrc.js
module.exports = { presets: [["next/babel"]], plugins: [["import", { libraryName: "antd", style: true }]], };

Storybook and gatsby

Storybook, Emotion, Gatsby. I've been struggling to add twin.macro to storybook in gatsby. I get warnings like the following

WARNING in ./node_modules/twin.macro/node_modules/babel-plugin-macros/dist/index.js 78:24-31
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
 @ ./node_modules/twin.macro/macro.js
 @ ./.storybook/preview.js
 @ ./.storybook/preview.js-generated-config-entry.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/storybook-init-framework-entry.js ./node_modules/@storybook/addon-docs/dist/frameworks/common/config.js-generated-other-entry.js ./node_modules/@storybook/addon-docs/dist/frameworks/react/config.js-generated-other-entry.js ./node_modules/@storybook/addon-links/dist/preset/addDecorator.js-generated-other-entry.js ./node_modules/@storybook/addon-actions/dist/preset/addDecorator.js-generated-other-entry.js ./node_modules/@storybook/addon-actions/dist/preset/addArgs.js-generated-other-entry.js ./node_modules/@storybook/addon-backgrounds/dist/preset/addDecorator.js-generated-other-entry.js ./node_modules/@storybook/addon-backgrounds/dist/preset/addParameter.js-generated-other-entry.js ./.storybook/preview.js-generated-config-entry.js ./.storybook/generated-stories-entry.js ./node_modules/webpack-hot-middleware/client.js?reload=true&quiet=false&noInfo=undefined

I tried to follow the instructions from emotion + storybook but it didn't quite work. I do have the twin.macro working in gatsby on its own though.

Babel macros fails

Hello, I have an issue with Parcel 2 and babel macros, I tried the documentation but I have this issue:

image

Can somebody help me?

Add further component library examples

nwb & neutrinojs are two popular tools used by component library authors to create and publish react components for distribution.

I experimented with adding twin.macro but received the following errors:

in ./node_modules/path-type/index.js
Module not found: Error: Can't resolve 'fs' in '.../node_modules/path-type'

in ./node_modules/resolve-from/index.js
Module not found: Error: Can't resolve 'fs' in '.../node_modules/resolve-from

in ./node_modules/resolve/lib/async.js
Module not found: Error: Can't resolve 'fs' in '.../node_modules/resolve/lib'

in ./node_modules/resolve/lib/sync.js
Module not found: Error: Can't resolve 'fs' in '.../node_modules/resolve/lib'

in ./node_modules/twin.macro/macro.js
Module not found: Error: Can't resolve 'fs' in '.../node_modules/twin.macro'

in ./node_modules/twin.macro/node_modules/cosmiconfig/dist/readFile.js
Module not found: Error: Can't resolve 'fs' in '.../node_modules/twin.macro/node_modules/cosmiconfig/dist'

in ./node_modules/resolve-from/index.js
Module not found: Error: Can't resolve 'module' in '.../node_modules/resolve-from'

would love to help out but my knowledge is limited in this space

Include 'styled-components/macro' in 'twin.macro'

When using styled-components with twin, it is annoying to add import 'styled-components/macro'; at the top of every file where you want to use it. Since importing twin is something you always have to do anyway - would it be possible to include the macro import from styled-components inside it (when configured accordingly in the config of course), thus simplifying the imports and preventing the silent errors that occur if you forget to add it?

ReferenceError: styled is not defined

In an otherwise well-working project with gatsby + styled-components (using tw prop, css prop, and tw import is working fine), I randomly can't get the styled import to work and get ReferenceError: styled is not defined if I try.

The error doesn't come up always. First I've managed to get it to work somehow.
After that, I could get it to fail again with above error by:

  • randomly creating a reference error in an unrelated file (and getting the correct error message).
  • afterwards correcting the reference error
  • now the "ReferenceError: styled is not defined" crops up again.
  • the issue is not fixed by deleting the gatsby cache and building again.
  • it's fixed by replacing the styled import from twin.macro by the one from 'styled-components'
  • it's not fixed by clearing/re-installing all node_modules.

Sorry I can't pin it down more precisely.

The setup: gatsby 2.26.1, styled-components 5.2.1, twin.macro 1.12.1. (But playing with some earlier twin version didn't appear to change the behaviour).
Running in a yarn workspaces setting if that matters.

package.json:

  "babelMacros": {
    "twin": {
      "preset": "styled-components",
      "config": "src/tailwind.config.js",
      "autoCssProp": true,
      "debugProp": true,
      "debugPlugins": false,
      "debug": false
    }
  },

I've tried replacing the preset with

      "styled": {
        "import": "default",
        "from": "styled-components"
      },
      "css": {
        "import": "css",
        "from": "styled-components/macro"
      },
      "global": {
        "import": "createGlobalStyle",
        "from": "styled-components"
      }

but that didn't change the outcome.

Btw: I love the twin project, your pace of adding new goodies is addictive..

Documentation for webpack5

Using with Next.js with webpack 5 enabled, I noticed as of webpack5 we cannot configure polyfill for fs with this.

ref: https://webpack.js.org/configuration/node/

I think with webpack5 we should do like this.

// next.config.js
module.exports = {
  webpack: (config, { isServer }) => {
    // Fixes packages that depend on fs/module module
    if (!isServer) {
      config.resolve = {
        fallback: {
          fs: 'empty', 
          module: 'empty'
        },
      }
    }

    return config
  },
}

I thought adding <details> section for this would be great.

Thank you for great tools and examples!

Typing component props with Stitches

I've set up twin macros with stitches following the examples but my styled-components export any type.

I was wondering if there's a way to type it so that I can autocomplete the props in VSCode

Screen Shot 2021-07-26 at 12 35 22 AM


Here's my twin.d.ts

import "twin.macro";
import { css as cssImport } from "@stitches/react";
import styledImport from "@stitches/react";

// Support a css prop when used with twins styled.div({}) syntax
type CSSProp<T = AnyIfEmpty<DefaultTheme>> = string | CSSObject;

declare module "react" {
  // The css prop
  interface HTMLAttributes<T> extends DOMAttributes<T> {
    css?: CSSProp;
    tw?: string;
  }
  // The inline svg css prop
  interface SVGProps<T> extends SVGProps<SVGSVGElement> {
    css?: CSSProp;
    tw?: string;
  }
}

// Support twins styled.div({}) syntax
type StyledTags = {
  [Tag in keyof JSX.IntrinsicElements]: CreateStyledComponent<
    JSX.IntrinsicElements[Tag]
  >;
};

declare module "twin.macro" {
  // The styled and css imports
  const styled: typeof StyledTags | typeof styledImport;
  const css: typeof cssImport;
}

Vite examples

Hello, I would like to know how to integrate twin.macro with Vite

Just tried it before but I got an issue here vitejs/vite#1942

Thanks before

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.