unocss/tailwindss 使用变量

2,122 阅读1分钟

image.png

// theme-var.ts
export const themeVar = {
  'arcoblue-5': '#09f5f5',
  'arcoblue-6': '#a9c94f'
  //...
}
// tsconfig.node.json
{
  "include": [
    "theme-var.*",
  ],
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "types": ["node"]
  }
}

添加设置,vscode插件同步提示

// unocss.config.ts
export default defineConfig({
  theme: {
    colors: {
      ...themeVar
    }
  }
})

// tailwind.config.ts
/** @type {import('tailwindcss').Config} */
export default {
  theme: {
    colors: {
      ...themeVar
    }
  }
}

unocss中也可以这样设置

// theme-var.ts
type ThemeVars = Record<string, string>

export function getThemeVarShortcuts() {
  const prefixList = ['border', 'bg', 'text', 'color']
  const vars = prefixList.reduce((acc, prefix) => {
    const res = Object.keys(themeVar).reduce((acc, key) => {
      const color = themeVar[key as keyof typeof themeVar]
      return { ...acc, [`${prefix}-${key}`]: `${prefix}-${color}` }
    }, {} as ThemeVars)
    return { ...acc, ...res }
  }, {} as ThemeVars)
  return vars
}

// unocss.config.ts
export default defineConfig({
  shortcuts: [{
    ...getThemeVarShortcuts()
  }]
})

如果在vite中用less替换变量,可以这样做

// vite.config.ts
export default defineConfig({
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
        modifyVars: {
          ...themeVar
        }
      }
    }
  }
})