March 18, 2025

Vite twin.marco & styled-components


[筆記] Vite 配置 twin.marco / styled-components 的配置

為了方便配置 styled-component 與 tailwind 的組合, 選擇了 twin.marco

安裝

// vite.config.ts
  plugins: [
    react({
      babel: {
        plugins: ["babel-plugin-macros", "babel-plugin-styled-components"],
      },
    }),
  ],

// package.json
  "babelMacros": {
    "twin": {
      "preset": "styled-components"
    }
  }
// twin.d.ts
import "twin.macro";

import type { CSSProp } from "styled-components";
import styledImport, { 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;
    tw?: string;
  }
  // The inline svg css prop
  interface SVGProps<T> extends SVGProps<SVGSVGElement> {
    css?: CSSProp;
    tw?: string;
  }
}

// The 'as' prop on styled components
declare global {
  namespace JSX {
    interface IntrinsicAttributes<T> extends DOMAttributes<T> {
      as?: string;
    }
  }
}