# m3-tailwind-colors 中文文档

规范地址：https://npmcn.com/package/m3-tailwind-colors/

版本：0\.4\.0
npm 元数据更新时间：2026-11-04T00:26:20.559Z
中文译文更新时间：2026-11-04T03:09:26.268Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/m3-tailwind-colors
原文对照：https://npmcn.com/package/m3-tailwind-colors/?lang=original
项目主页：https://github.com/somteacodes/m3tailwindcolorgenerator#readme
源码仓库：https://github.com/somteacodes/m3tailwindcolorgenerator

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：188 kB，22 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18
- 运行依赖：2 个
- 首次发布：2024-08-27T02:23:00.132Z
- 最新版本发布：2026-11-04T00:26:20.365Z
- 已发布版本数：10（近 12 个月 4 个）

## 中文简介

为Tailwind CSS （v3和v4）和NativeWind生成材质3种颜色。

## 安装

```sh
npm install m3-tailwind-colors
```

也可以使用：`pnpm add m3-tailwind-colors`、`yarn add m3-tailwind-colors`、`bun add m3-tailwind-colors`

## README

# M3顺风色

**M3顺风色** 是一个实用程序包，它基于材质3颜色系统生成材质3颜色，用于Tailwind CSS和NativeWind。

## 顺风CSS v4支持现已可用

-   **使用顺风v4？** 查看我们的 [CLI和CSS主题生成](https://npmcn.com/package/m3-tailwind-colors/#readme-tailwind-v4-usage) 在下面。
-   **从v3迁移到v4？** 查看我们的 [迁移指南](https://npmcn.com/package/m3-tailwind-colors/#readme-migrating-to-v4)。

## 演示

[查看现场演示](https://deesign.dev/)

## 为什么M3顺风色？

Material 3提供了一个强大的颜色系统，但手动生成和管理这些调色板的顺风CSS可能是压倒性的。

**这个包解决了这个问题：**

-   **自动创建调色板**：从单一颜色生成所有所需的调色板（主要，次要，错误，表面等）。
-   **确保可访问性**：使用官方的材质颜色实用程序来实现对比度。
-   **类型安全**为React Native （NativeWind）和Tailwind配置提供TypeScript支持。
-   **一致性**：保证你的光明和黑暗模式完全同步。

简单地选择一个原色，让工具处理复杂的色彩科学。

## 特性

-   生成一个基于原色的材质3颜色的完整调色板。
-   **新:** 顺风CSS v4原生支持 `@theme` CSS变量
-   **新:** 轻松生成主题的CLI工具
-   轻松集成与顺风CSS或NativeWind项目。
-   支持浅色和深色配色方案。
-   十六进制和OKLCH颜色格式支持。

阅读更多关于它是如何工作的 [在这里](https://m3.material.io/styles/color/system/how-the-system-works)

> **它是如何工作的：** 当只提供原色时，它被用作种子色来生成整个材质3调色板，包括二级，三级，表面，以及根据材质设计3指南的所有其他颜色标记。

## 安装

通过npm安装包：

```bash
npm install m3-tailwind-colors
```

这将自动安装必要的依赖项，包括 `@material/material-color-utilities`。

> **注意:** 在使用此包之前，必须在项目中设置顺风CSS。

## 快速启动

### 对于顺风v4

```bash
# Initialize configuration
npx m3-tailwind-colors init --primary "#0062A8"

# Generate CSS theme
npx m3-tailwind-colors generate

# Import in your main CSS file
# @import "./src/m3-theme.css";
```

### 顺风v3

```javascript
// tailwind.config.js
const { M3TailwindConfigColors } = require("m3-tailwind-colors");

module.exports = {
  theme: {
    extend: {
      colors: M3TailwindConfigColors({ primary: "#0062A8" })
    }
  }
};
```

* * *

## 顺风v4使用

### CLI命令

#### 初始化配置

创建一个 `m3-colors.config.json` 文件默认值：

```bash
npx m3-tailwind-colors init --primary "#0062A8"
```

**选项:**

-   `--primary <color>` -原色（十六进制格式）
-   `--secondary <color>` -副色（可选）
-   `--tertiary <color>` -三色（可选）
-   `--scheme <name>` -配色方案（内容、表现力等）
-   `--contrast <number>` -对比度（-1 ~ 1）
-   `--format <format>` -颜色格式（十六进制或oklch）
-   `--mode <mode>` —输出模式（组合、亮、暗）
-   `--output <path>` —输出CSS文件路径
-   `--config <path>` —配置文件路径

#### 生成的主题

生成CSS主题文件：

```bash
npx m3-tailwind-colors generate
```

**选项:**

-   `--include-tailwind-import` ——包括 `@import "tailwindcss"` 在输出
-   `--dark-mode <strategy>` -暗模式策略： `media` (默认), `class`,或 `none`
-   `--target <platform>` -目标平台： `web` (默认)或 `nativewind`
-   `--colors-output <path>` - TypeScript颜色文件的输出路径（仅限NativeWind）

这是你的 `m3-colors.config.json` 并输出如下CSS（默认值） `media` 策略):

```css
@theme {
  --color-primary: #3b82f6;
  --color-on-primary: #ffffff;
  --color-surface: #fafafa;
  /* ... all Material 3 color tokens */
}

@media (prefers-color-scheme: dark) {
  :root {
    --color-primary: #60a5fa;
    /* ... dark mode colors */
  }
}
```

与 `--dark-mode class`，深色适用于当a `.dark` 类在一个祖先元素上：

```css
@custom-variant dark (&:where(.dark, .dark *));

@theme {
  --color-primary: #3b82f6;
  /* ... */
}

@variant dark {
  --color-primary: #60a5fa;
  /* ... */
}
```

与 `--dark-mode none`只有光 `@theme` 块作为输出。

### 编程API

```typescript
import { generateM3ThemeCSS } from 'm3-tailwind-colors/v4';
import fs from 'fs';

const css = generateM3ThemeCSS({
  colors: {
    primary: "#0062A8",
    secondary: "#CBF7ED",
    tertiary: "#F98948"
  },
  format: "hex",      // or "oklch"
  mode: "combined",   // or "light" or "dark"
  scheme: "content",  // Material scheme type
  contrast: 0,        // -1 to 1
  includeTailwindImport: false, // Include @import "tailwindcss"
  darkModeStrategy: "media"     // or "class" or "none"
});

fs.writeFileSync('./src/theme.css', css);
```

### 配置文件

例子 `m3-colors.config.json`：

```json
{
  "colors": {
    "primary": "#0062A8",
    "secondary": "#CBF7ED",
    "tertiary": "#F98948",
    "success": "#16A34A",
    "error": "#EF4444",
    "warning": "#D14700",
    "info": "#0055D1"
  },
  "scheme": "content",
  "contrast": 0,
  "format": "hex",
  "mode": "combined",
  "output": "src/m3-theme.css"
}
```

> **注意:** 您可以添加任何自定义颜色键(如 `success`， `warning`， `info`)，它将为该颜色生成一个完整的调色板。

* * *

## NativeWind用法（React Native）

为NativeWind项目生成材质3的颜色 `--target nativewind` 国旗。

### 快速启动

```bash
npx m3-tailwind-colors generate --target nativewind --primary "#0062A8"
```

这将生成两个文件：

-   `global.css` —NativeWind格式的CSS变量
-   `theme/m3-colors.ts` - React Native的TypeScript颜色

### 生成的CSS格式

```css
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --primary: 0 74 129;
    --on-primary: 255 255 255;
    --android-primary: 0 74 129;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --primary: 160 201 255;
    }
  }
}
```

### 生成的TypeScript颜色

```typescript
export const COLORS = {
  light: {
    primary: 'rgb(0, 74, 129)',
    onPrimary: 'rgb(255, 255, 255)',
  },
  dark: {
    primary: 'rgb(160, 201, 255)',
  },
} as const;
```

### 自定义输出路径

```bash
npx m3-tailwind-colors generate \
  --target nativewind \
  --primary "#0062A8" \
  --output "src/global.css" \
  --colors-output "src/theme/colors.ts"
```

### 配置文件

添加 `target` 到你的 `m3-colors.config.json`：

```json
{
  "colors": { "primary": "#0062A8" },
  "target": "nativewind",
  "colorsOutput": "theme/m3-colors.ts"
}
```

### 从NativeWindUI Starter迁移

如果你使用NativeWindUI starter模板，生成的M3颜色使用不同的名称。更新你的 `theme/index.ts`：

```typescript
// theme/index.ts
import { Theme, DefaultTheme, DarkTheme } from '@react-navigation/native';
import { COLORS } from './colors';

const NAV_THEME: { light: Theme; dark: Theme } = {
  light: {
    dark: false,
    colors: {
      background: COLORS.light.background,
      border: COLORS.light.outlineVariant,     // was: grey5
      card: COLORS.light.surface,               // was: card
      notification: COLORS.light.error,         // was: destructive
      primary: COLORS.light.primary,
      text: COLORS.light.onBackground,          // was: COLORS.black
    },
    fonts: DefaultTheme.fonts,
  },
  dark: {
    dark: true,
    colors: {
      background: COLORS.dark.background,
      border: COLORS.dark.outlineVariant,       // was: grey5
      card: COLORS.dark.surfaceContainer,       // was: grey6
      notification: COLORS.dark.error,          // was: destructive
      primary: COLORS.dark.primary,
      text: COLORS.dark.onBackground,           // was: COLORS.white
    },
    fonts: DarkTheme.fonts,
  },
};

export { NAV_THEME };
```

**颜色名称映射：**

| NativeWindUI | M3等效 |
| --- | --- |
| `grey6` | `surfaceContainerLowest` |
| `grey5` | `outlineVariant` |
| `card` | `surface` 或 `surfaceContainer` |
| `destructive` | `error` |
| `COLORS.white` | 硬编码 `'rgb(255,255,255)'` 或使用 `onPrimary` |
| `COLORS.black` | 硬编码 `'rgb(0,0,0)'` 或使用 `onBackground` |

* * *

## 顺风v3使用情况

要在顺风CSS配置中使用生成的颜色，请遵循以下步骤：

-   **导入和生成颜色：** 使用 `M3TailwindConfigColors` 函数生成基于原色的材质3调色板。
    
-   **扩展顺风的颜色：** 将生成的颜色添加到扩展中。您的Tailwind配置的颜色部分。
    

配置示例：

```javascript
/** @type {import('tailwindcss').Config} */

const { M3TailwindConfigColors } = require("m3-tailwind-colors");

const generatedColors = M3TailwindConfigColors({
  primary: "#CE7E00", // Replace with your primary color
  otherCustomColor: "#65ff34", //optional
});

module.exports = {
  content: ["./app/**/*.{js,jsx,ts,tsx}", "./components/**/*.{js,jsx,ts,tsx}"],
  presets: [require("nativewind/preset")],
  theme: {
    extend: {
      colors: {
        ...generatedColors,
      },
    },
  },
  plugins: [],
};
```

* * *

## React Native样式的使用

这个包导出了一个函数，可以用来为React Native生成颜色：

```typescript
import { M3TailwindRNColors } from "m3-tailwind-colors";

const M3colors = M3TailwindRNColors(
  { primary: "#CE7E00" },
  {
    scheme: "content",
    contrast: 0,
  }
);

export const Colors = M3colors;
```

然后在你的React Native文件中使用：

```typescript
<View
  style={{
    backgroundColor:
      colorScheme === "dark" ? Colors.dark.surface : Colors.light.surface,
  }}
>
  {children}
</View>
```

* * *

## 迁移到v4

### 先决条件

```bash
npm install tailwindcss@next
```

### 一步一步的迁移

**1\. 生成v4主题：**

```bash
npx m3-tailwind-colors init --primary "#0062A8"
npx m3-tailwind-colors generate
```

**2\. 更新你的CSS条目文件：**

```css
/* Add to your main CSS file */
@import "./m3-theme.css";
```

**3\. 移除顺风配置（可选）：**

```bash
# tailwind.config.js can be deleted if only used for colors
rm tailwind.config.js
```

**4\. 不需要更改类名！**

现有的实用程序类继续工作：

-   `bg-primary` -仍然有效
-   `text-on-primary` -仍然有效
-   所有材质3的颜色令牌保持不变

* * *

## 生成的颜色

生成的调色板包括所有材质3颜色令牌：

-   **主:** 主，非主，主-容器，非主-容器，逆主
-   **二级:** Secondary, on-secondary, Secondary -container, on-secondary-container
-   **三级:** 叔碳，对叔碳，对叔碳，对叔碳
-   **修复:** Primary-fixed, Primary-fixed -dim, on-primary-fixed, on-primary-fixed-variant，对于secondary和tertiary同样有四个
-   **错误:** 错误，非错误，错误容器，非错误容器
-   **表面:** 表面，表面上，表面变化，表面变化，表面暗淡，表面明亮，表面容器最低，表面容器低，表面容器高，表面容器最高，反表面，反表面，表面着色
-   **背景:** 背景、研究背景
-   **大纲:** 轮廓,outline-variant
-   **其他:** 玻璃,影子

### 固定的颜色

固定的颜色在明暗模式下保持相同的值。将它们用于不应该更改的元素 主题切换时的外观，如品牌横幅或照片上的芯片：

```html
<div class="bg-primary-fixed text-on-primary-fixed">Same in light and dark</div>
```

在默认对比度下(`0`)的明暗值是相同的。在较高的对比度水平下， Material 3可能会在每个模式下稍微调整它们以保持文本的可读性。

### 自定义颜色

每个自定义颜色(例如： `success`)生成八个令牌：

-   `success`， `on-success`， `success-container`， `on-success-container`
-   `success-fixed`， `success-fixed-dim`， `on-success-fixed`， `on-success-fixed-variant`

在camelCase输出中，名称是 `success`， `onSuccess`， `successContainer`， `onSuccessContainer`， `successFixed`， `successFixedDim`， `onSuccessFixed` 和 `onSuccessFixedVariant`。

* * *

## 参数

这个 `M3TailwindConfigColors` 和 `M3TailwindRNColors` 函数接受:

```typescript
M3TailwindRNColors(
  {
    primary: '#ff0000', // Required: Primary color in hex format
    secondary: '#ffff00', // Optional: Auto-generated if not provided
    tertiary: '#0000ff', // Optional: Auto-generated if not provided
    customname: '#00ff00', // Optional: Any custom colors
  },
  {
    scheme: 'content', // Optional: 'content', 'expressive', 'fidelity', 'monochrome', 'neutral', 'tonalSpot', 'vibrant'
    contrast: 0, // Optional: -1 (less contrast) to 1 (more contrast)
  },
  true // Optional: Use kebab-case (default: false)
)
```

* * *

## 贡献

欢迎投稿！请参阅 [CONTRIBUTING.md](https://npmcn.com/package/m3-tailwind-colors/CONTRIBUTING.md) 为指导方针。

## 许可证

MIT许可证-参见 [许可证](https://npmcn.com/package/m3-tailwind-colors/LICENSE) 获取详细信息。

## 常见问题

### m3-tailwind-colors 是什么？

为Tailwind CSS （v3和v4）和NativeWind生成材质3种颜色。

### 如何安装 m3-tailwind-colors？

在项目目录运行 npm install m3-tailwind-colors，或使用 pnpm add / yarn add / bun add。它还提供命令行工具 m3-tailwind-colors，可以用 npx m3-tailwind-colors 直接运行。

### m3-tailwind-colors 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### m3-tailwind-colors 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### m3-tailwind-colors 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### m3-tailwind-colors 可以商用吗？

m3-tailwind-colors 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### m3-tailwind-colors 还在维护吗？

最新版本 0\.4\.0 发布于 2026/11/04（1 天前）；至今共发布 10 个版本，其中过去 12 个月发布了 4 个；首次发布于 2024/08/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

