# weapp-tailwindcss API 与配置参考
> 包含插件配置、API 细节、常见问题与迁移指南,适合回答配置/兼容性问题。
This file contains all documentation content in a single document following the llmstxt.org standard.
## weapp-tailwindcss
## 配置项
- [UserDefinedOptions 总览](interfaces/UserDefinedOptions.md)
- [✅ 重要配置](options/important.md)
- [🧩 文件匹配](options/matchers.md)
- [🧭 生命周期](options/lifecycle.md)
- [⚙️ 一般配置](options/general.md)
## 接口
- [🗂️ 其他接口](other-interfaces.md)
---
## ApplyOptions
Preferred options for runtime patch behavior.
## 属性
### overwrite?
> `optional` **overwrite**: `boolean`
Whether patched files can be overwritten on disk.
***
### exposeContext?
> `optional` **exposeContext**: `boolean | ExposeContextOptions`
Whether to expose runtime Tailwind contexts (or configure how they are exposed).
***
### extendLengthUnits?
> `optional` **extendLengthUnits**: `false | ExtendLengthUnitsOptions`
Extends the length-unit patch or disables it entirely.
---
## CacheOptions
Configures how the Tailwind class cache is stored and where it lives on disk.
## 属性
### enabled?
> `optional` **enabled**: `boolean`
Whether caching is enabled.
***
### cwd?
> `optional` **cwd**: `string`
Working directory used when resolving cache paths.
***
### dir?
> `optional` **dir**: `string`
Directory where cache files are written.
***
### file?
> `optional` **file**: `string`
Cache filename. Defaults to `class-cache.json` inside the derived cache folder
when omitted.
***
### strategy?
> `optional` **strategy**: `CacheStrategy`
Strategy used when merging new class lists with an existing cache.
***
### driver?
> `optional` **driver**: `CacheDriver`
Backend used to persist the cache (`file`, `memory`, or `noop`). Defaults to `file`.
---
## DisabledOptions
禁用插件功能的细粒度选项。
## 添加于
^4.2.0
## 备注
适用于需要仅关闭部分行为(例如主插件流程),但保留其他预处理能力(如 Tailwind v4 的 `@import "tailwindcss"` 到 `@import "weapp-tailwindcss/index.css"` 的重写)。
## 属性
### plugin?
> `optional` **plugin**: `boolean`
禁用主插件流程,等同于 `disabled: true`。
#### 默认值
```ts
false
```
***
### rewriteCssImports?
> `optional` **rewriteCssImports**: `boolean`
禁用对 `@import "tailwindcss"` 到 `@import "weapp-tailwindcss/index.css"` 的预处理重写。
#### 默认值
```ts
false
```
---
## ExtractOptions
Preferred options for extraction output behavior.
## 属性
### write?
> `optional` **write**: `boolean`
Whether to produce an output file.
***
### file?
> `optional` **file**: `string`
Optional absolute or relative path to the output file.
***
### format?
> `optional` **format**: `"json" | "lines"`
Output format, defaults to JSON when omitted.
***
### pretty?
> `optional` **pretty**: `number | boolean`
Pretty-print spacing (truthy value enables indentation).
***
### removeUniversalSelector?
> `optional` **removeUniversalSelector**: `boolean`
Whether to strip the universal selector (`*`) from the final list.
---
## TailwindCssOptions
High-level Tailwind patch configuration shared across versions.
## 属性
### config?
> `optional` **config**: `string`
Path to a Tailwind config file when auto-detection is insufficient.
***
### cwd?
> `optional` **cwd**: `string`
Custom working directory used when resolving config-relative paths.
***
### postcssPlugin?
> `optional` **postcssPlugin**: `string`
Optional PostCSS plugin name to use instead of the default.
***
### version?
> `optional` **version**: `2 | 3 | 4`
Explicit Tailwind CSS major version used by the current project. When omitted, the installed package version is inferred.
***
### packageName?
> `optional` **packageName**: `string`
Tailwind package name if the project uses a fork.
***
### resolve?
> `optional` **resolve**: `PackageResolvingOptions`
Package resolution options forwarded to `local-pkg`.
***
### v2?
> `optional` **v2**: `TailwindV2Options`
Overrides applied when patching Tailwind CSS v2.
***
### v3?
> `optional` **v3**: `TailwindV3Options`
Overrides applied when patching Tailwind CSS v3.
***
### v4?
> `optional` **v4**: `TailwindV4Options`
Options specific to Tailwind CSS v4 patching.
---
## TailwindCssPatchOptions
Root configuration consumed by the Tailwind CSS patch runner.
## 属性
### projectRoot?
> `optional` **projectRoot**: `string`
Base directory used when resolving Tailwind resources.
Defaults to `process.cwd()`.
***
### tailwindcss?
> `optional` **tailwindcss**: `TailwindCssOptions`
Preferred Tailwind runtime configuration.
***
### apply?
> `optional` **apply**: `ApplyOptions`
Preferred patch toggles.
***
### extract?
> `optional` **extract**: `ExtractOptions`
Preferred extraction output settings.
***
### filter()?
> `optional` **filter()**: `((className: string) => boolean)`
Optional function that filters final class names.
#### 参数
##### className
`string`
#### 返回
`boolean`
***
### cache?
> `optional` **cache**: `boolean | CacheOptions`
Cache configuration or boolean to enable/disable quickly.
---
## TailwindV2Options
Configuration specific to Tailwind CSS v2 patching flows.
## 属性
### config?
> `optional` **config**: `string`
Path to a Tailwind config file when auto-detection is insufficient.
***
### cwd?
> `optional` **cwd**: `string`
Custom working directory used when resolving config-relative paths.
***
### postcssPlugin?
> `optional` **postcssPlugin**: `string`
Optional PostCSS plugin name to use instead of the default.
---
## TailwindV3Options
Configuration specific to Tailwind CSS v3 patching flows.
## 属性
### config?
> `optional` **config**: `string`
Path to a Tailwind config file when auto-detection is insufficient.
***
### cwd?
> `optional` **cwd**: `string`
Custom working directory used when resolving config-relative paths.
***
### postcssPlugin?
> `optional` **postcssPlugin**: `string`
Optional PostCSS plugin name to use instead of the default.
---
## TailwindV4Options
Additional configuration specific to Tailwind CSS v4 extraction.
## 属性
### base?
> `optional` **base**: `string`
Base directory used when resolving v4 content sources and configs.
***
### css?
> `optional` **css**: `string`
Raw CSS passed directly to the v4 design system.
***
### cssEntries?
> `optional` **cssEntries**: `string[]`
Set of CSS entry files that should be scanned for `@config` directives.
***
### sources?
> `optional` **sources**: `SourceEntry[]`
Overrides the content sources scanned by the oxide scanner.
---
## UserDefinedOptions
## 分组入口
- [✅ 重要配置](../options/important.md) (17)
- [🧩 文件匹配](../options/matchers.md) (6)
- [🧭 生命周期](../options/lifecycle.md) (4)
- [⚙️ 一般配置](../options/general.md) (17)
---
## ⚙️ 一般配置
本页收录 17 个配置项,来源于 `UserDefinedOptions`。
## 配置一览
| 配置项 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| [supportCustomLengthUnitsPatch](#supportcustomlengthunitspatch) | boolean | ILengthUnitsPatchOptions | — | 控制 Tailwind 自定义长度单位补丁。 |
| [appType](#apptype) | AppType | — | 声明所使用的框架类型。 |
| [arbitraryValues](#arbitraryvalues) | IArbitraryValues | — | TailwindCSS 任意值的相关配置。 |
| [jsPreserveClass](#jspreserveclass) | (keyword: string) => boolean | undefined | 保留所有带 `*` js字符串字面量 | 控制 JS 字面量是否需要保留。 |
| [staleClassNameFallback](#staleclassnamefallback) | boolean | — | 兼容字段:不再参与 JS 候选判定。 |
| [jsArbitraryValueFallback](#jsarbitraryvaluefallback) | boolean | "auto" | — | 控制 JS 任意值类名在 classNameSet 异常时的受控兜底策略。 |
| [replaceRuntimePackages](#replaceruntimepackages) | boolean | Record | — | 是否替换运行时依赖包名。 |
| [disabledDefaultTemplateHandler](#disableddefaulttemplatehandler) | boolean | false | 禁用默认的 `wxml` 模板替换器。 |
| [tailwindcssBasedir](#tailwindcssbasedir) | string | — | 指定用于获取 Tailwind 上下文的路径。 |
| [cache](#cache) | boolean | ICreateCacheReturnType | — | 控制缓存策略。 |
| [babelParserOptions](#babelparseroptions) | (Partial & { cache?: boolean; cacheKey?: string; }) | — | `@babel/parser` 的配置选项。 |
| [cssChildCombinatorReplaceValue](#csschildcombinatorreplacevalue) | string | string[] | 'view + view' | 自定义 Tailwind 子组合器的替换值。 |
| [postcssOptions](#postcssoptions) | Partial> | — | `postcss` 的配置选项。 |
| [cssRemoveHoverPseudoClass](#cssremovehoverpseudoclass) | boolean | `true` | 是否移除 CSS 中的 `:hover` 选择器。 |
| [cssRemoveProperty](#cssremoveproperty) | boolean | `true` | 是否移除 `@property` 节点。 |
| [tailwindcssPatcherOptions](#tailwindcsspatcheroptions) | TailwindCssPatchOptions | — | 自定义 patcher 参数。 |
| [logLevel](#loglevel) | "info" | "warn" | "error" | "silent" | — | 控制命令行日志输出级别。 |
## 详细说明
### supportCustomLengthUnitsPatch
> 可选 | 类型: `boolean | ILengthUnitsPatchOptions`
控制 Tailwind 自定义长度单位补丁。
#### 参阅
://github.com/sonofmagic/weapp-tailwindcss/issues/110
#### 备注
TailwindCSS 3.2.0 起对任意值执行长度单位校验,会将未声明的 `rpx` 识别为颜色。本选项默认开启以注入 `rpx` 支持。当 Node.js 在插件执行前已缓存 `tailwindcss` 模块时,首轮运行可能未生效,可通过在 `postinstall` 中执行 `weapp-tw patch` 提前打补丁。
```diff
"scripts": {
+ "postinstall": "weapp-tw patch"
}
```
### appType
> 可选 | 类型: `AppType`
声明所使用的框架类型。
#### 备注
用于辅助定位主要的 CSS bundle,以便默认的 `mainCssChunkMatcher` 做出更准确的匹配,未传入时将尝试自动猜测变量注入位置。
### arbitraryValues
> 可选 | 类型: `IArbitraryValues`
TailwindCSS 任意值的相关配置。
### jsPreserveClass
> 可选 | 类型: `(keyword: string) => boolean | undefined` | 默认值: `保留所有带 \`*\` js字符串字面量` | 版本: ^2.6.1
控制 JS 字面量是否需要保留。
#### 备注
当 Tailwind 与 JS 字面量冲突时,可通过回调返回 `true` 保留当前值,返回 `false` 或 `undefined` 则继续转义。默认保留所有带 `*` 的字符串字面量。
#### 默认值
```ts
保留所有带 `*` js字符串字面量
```
#### 参数
##### keyword
`string`
#### 返回
`boolean | undefined`
### staleClassNameFallback
> 可选 | 类型: `boolean`
兼容字段:不再参与 JS 候选判定。
#### 备注
JS 转译统一采用 `classNameSet` 精确匹配策略,仅转换 tailwindcss-patch 提供的类名集合。
### jsArbitraryValueFallback
> 可选 | 类型: `boolean | "auto"`
控制 JS 任意值类名在 classNameSet 异常时的受控兜底策略。
#### 备注
为避免误伤业务字符串,兜底仅在 class 语义上下文生效。
- `false`:关闭兜底;
- `true`:始终开启受控兜底;
- `'auto'`:仅 TailwindCSS v4 且 classNameSet 为空时启用。
### replaceRuntimePackages
> 可选 | 类型: `boolean | Record`
是否替换运行时依赖包名。
#### 备注
适用于运行时包名需要重定向的场景,例如:
- 小程序侧无法直接安装 `tailwind-merge`/`class-variance-authority`/`tailwind-variants`,需要替换为内置的 weapp 版本。
- 企业内私有镜像/多包发布导致运行时包名不同,希望在转换后统一到目标包名。
传入 `true` 使用内置替换表,或传入对象自定义映射。
#### 示例
```ts
replaceRuntimePackages: {
'tailwind-merge': '@weapp-tailwindcss/merge',
'class-variance-authority': '@weapp-tailwindcss/cva',
}
```
### disabledDefaultTemplateHandler
> 可选 | 类型: `boolean` | 默认值: `false` | 版本: ^2.6.2
禁用默认的 `wxml` 模板替换器。
#### 备注
启用后模板匹配完全交由 [`customAttributes`](/docs/api/options/important#customattributes) 管理,需要自行覆盖默认的 `class` / `hover-class` 等匹配规则。
#### 默认值
```ts
false
```
### tailwindcssBasedir
> 可选 | 类型: `string` | 版本: ^2.9.3
指定用于获取 Tailwind 上下文的路径。
#### 备注
在 linked 或 monorepo 场景下可手动指向目标项目的 `package.json` 所在目录。
### cache
> 可选 | 类型: `boolean | ICreateCacheReturnType` | 版本: ^3.0.11
控制缓存策略。
### babelParserOptions
> 可选 | 类型: `(Partial & { cache?: boolean; cacheKey?: string; })` | 版本: ^3.2.0
`@babel/parser` 的配置选项。
### cssChildCombinatorReplaceValue
> 可选 | 类型: `string | string[]` | 默认值: `'view + view'`
自定义 Tailwind 子组合器的替换值。
#### 备注
为兼容小程序缺乏 `:not([hidden])~` 支持的限制,默认会将 `.space-x-4` 等选择器替换为 `view + view`。可传入字符串或字符串数组以扩展适用标签。
```css
// 数组示例
.space-y-4>view + view,text + text{}
// 字符串示例
.space-y-4>view,text,button,input ~ view,text,button,input{}
```
#### 默认值
```ts
'view + view'
```
### postcssOptions
> 可选 | 类型: `Partial>` | 版本: ^3.2.0
`postcss` 的配置选项。
### cssRemoveHoverPseudoClass
> 可选 | 类型: `boolean` | 默认值: `\`true\`` | 版本: ^3.2.1
是否移除 CSS 中的 `:hover` 选择器。
#### 参阅
://github.com/sonofmagic/weapp-tailwindcss/issues/293
#### 备注
小程序不支持 `:hover`,需要使用组件的 `hover-class`,因此默认删除相关节点。
#### 默认值
`true`
### cssRemoveProperty
> 可选 | 类型: `boolean` | 默认值: `\`true\`` | 版本: ^4.1.2
是否移除 `@property` 节点。
#### 备注
微信小程序可识别 `@property`,但支付宝暂不支持,默认移除以避免构建失败。
#### 默认值
`true`
### tailwindcssPatcherOptions
> 可选 | 类型: `TailwindCssPatchOptions`
自定义 patcher 参数。
### logLevel
> 可选 | 类型: `"info" | "warn" | "error" | "silent"`
控制命令行日志输出级别。
#### 备注
默认 `info`,可设置为 `silent` 屏蔽全部输出。
---
## ✅ 重要配置
本页收录 17 个配置项,来源于 `UserDefinedOptions`。
## 配置一览
| 配置项 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| [disabled](#disabled) | boolean | DisabledOptions | — | 是否禁用此插件。 |
| [customAttributes](#customattributes) | ICustomAttributes | — | 自定义 `wxml` 标签属性的转换规则。 |
| [customReplaceDictionary](#customreplacedictionary) | Record | MappingChars2String | 自定义 class 名称的替换字典。 |
| [ignoreTaggedTemplateExpressionIdentifiers](#ignoretaggedtemplateexpressionidentifiers) | (string | RegExp)[] | ['weappTwIgnore'] | 忽略指定标签模板表达式中的标识符。 |
| [ignoreCallExpressionIdentifiers](#ignorecallexpressionidentifiers) | (string | RegExp)[] | — | 忽略指定调用表达式中的标识符。 |
| [cssPreflight](#csspreflight) | CssPreflightOptions | — | 控制在视图节点上注入的 CSS 预设。 |
| [cssPreflightRange](#csspreflightrange) | "all" | — | 控制 `cssPreflight` 注入的 DOM 选择器范围。 |
| [cssCalc](#csscalc) | boolean | (string | RegExp)[] | CssCalcOptions | — | 预计算 CSS 变量或 `calc` 表达式的结果。 |
| [injectAdditionalCssVarScope](#injectadditionalcssvarscope) | boolean | false | 是否额外注入 `tailwindcss css var scope`。 |
| [rewriteCssImports](#rewritecssimports) | boolean | true | 是否在 webpack/vite 阶段自动把 CSS 中的 `@import 'tailwindcss'` 映射为 `weapp-tailwindcss`。 |
| [cssSelectorReplacement](#cssselectorreplacement) | { root?: string | string[] | false; universal?: string | string[] | false; } | 详见下方 | 控制 CSS 选择器的替换规则。 |
| [rem2rpx](#rem2rpx) | boolean | Rem2rpxOptions | — | rem 到 rpx 的转换配置。 |
| [px2rpx](#px2rpx) | boolean | Px2rpxOptions | — | px 到 rpx 的转换配置。 |
| [unitsToPx](#unitstopx) | boolean | UnitsToPxOptions | — | 多单位转 px 的转换配置。 |
| [cssPresetEnv](#csspresetenv) | PresetEnvOptions | — | `postcss-preset-env` 的配置项。 |
| [tailwindcss](#tailwindcss) | import("/Users/yangqiming/Documents/GitHub/weapp-tailwindcss/packages/weapp-tailwindcss/src/typedoc.export").TailwindCssOptions | — | 为不同版本的 Tailwind 配置行为。 |
| [cssEntries](#cssentries) | string[] | — | 指定 tailwindcss@4 的入口 CSS。 |
## 详细说明
### disabled
> 可选 | 类型: `boolean | DisabledOptions`
是否禁用此插件。
#### 备注
在多平台构建场景下常用:小程序构建保持默认,非小程序环境(H5、App)传入 `true` 即可跳过转换。
#### 示例
```ts
// uni-app vue3 vite
const isH5 = process.env.UNI_PLATFORM === 'h5'
const isApp = process.env.UNI_PLATFORM === 'app'
const disabled = isH5 || isApp
uvtw({
disabled,
})
```
### customAttributes
> 可选 | 类型: `ICustomAttributes`
自定义 `wxml` 标签属性的转换规则。
#### 备注
默认会转换所有标签上的 `class` 与 `hover-class`。此配置允许通过 `Map` 或对象为特定标签指定需要转换的属性字符串或正则表达式数组。
- 使用 `'*'` 作为键可为所有标签追加通用规则。
- 支持传入 `Map` 以满足复杂匹配需求。
- 常见场景包括通过组件 `prop` 传递类名,或对三方组件的自定义属性做匹配,更多讨论见 [issue#129](https://github.com/sonofmagic/weapp-tailwindcss/issues/129#issuecomment-1340914688) 与 [issue#134](https://github.com/sonofmagic/weapp-tailwindcss/issues/134#issuecomment-1351288238)。
如果自定义规则已经覆盖默认的 `class`/`hover-class`,可开启 [`disabledDefaultTemplateHandler`](/docs/api/options/general#disableddefaulttemplatehandler) 以关闭内置模板处理器。
#### 示例
```js
const customAttributes = {
'*': [/[A-Za-z]?[A-Za-z-]*[Cc]lass/],
'van-image': ['custom-class'],
'ice-button': ['testClass'],
}
```
### customReplaceDictionary
> 可选 | 类型: `Record` | 默认值: `MappingChars2String`
自定义 class 名称的替换字典。
#### 备注
默认策略会将小程序不允许的字符映射为等长度的替代字符串,因此无法通过结果反推出原始类名。如需完全自定义,可传入 `Record`,只需确保生成的类名不会与已有样式冲突。示例参考 [dic.ts](https://github.com/sonofmagic/weapp-core/blob/main/packages/escape/src/dic.ts)。
#### 默认值
```ts
MappingChars2String
```
### ignoreTaggedTemplateExpressionIdentifiers
> 可选 | 类型: `(string | RegExp)[]` | 默认值: `['weappTwIgnore']` | 版本: ^4.0.0
忽略指定标签模板表达式中的标识符。
#### 备注
当模板字符串被这些标识符包裹时,将跳过转义处理。
#### 默认值
```ts
['weappTwIgnore']
```
### ignoreCallExpressionIdentifiers
> 可选 | 类型: `(string | RegExp)[]` | 版本: ^4.0.0
忽略指定调用表达式中的标识符。
#### 备注
使用这些方法包裹的模板字符串或字符串字面量会跳过转义,常与 `@weapp-tailwindcss/merge` 配合(如 `['twMerge', 'twJoin', 'cva']`)。
### cssPreflight
> 可选 | 类型: `CssPreflightOptions`
控制在视图节点上注入的 CSS 预设。
#### 参阅
://github.com/sonofmagic/weapp-tailwindcss/issues/7
#### 备注
默认会向所有 `view`/`text` 元素注入 Tailwind 风格的基础样式,可通过此配置禁用、调整或补充规则,受 `cssPreflightRange` 影响。
#### 示例
```js
cssPreflight: {
'box-sizing': 'border-box',
'border-width': '0',
'border-style': 'solid',
'border-color': 'currentColor',
}
cssPreflight: false
cssPreflight: {
'box-sizing': false,
background: 'black',
}
```
### cssPreflightRange
> 可选 | 类型: `"all"`
控制 `cssPreflight` 注入的 DOM 选择器范围。
#### 参阅
://github.com/sonofmagic/weapp-tailwindcss/pull/62
#### 备注
仅 `view`、`text` 及其伪元素会受影响。设置为 `'all'` 可以覆盖所有元素,此时需自行处理与宿主默认样式的冲突。
### cssCalc
> 可选 | 类型: `boolean | (string | RegExp)[] | CssCalcOptions` | 版本: ^4.3.0
预计算 CSS 变量或 `calc` 表达式的结果。
#### 备注
解决部分机型对 `calc` 计算不一致的问题,可传入布尔值、选项对象或自定义匹配列表(支持正则)。在启用计算后,可通过 `includeCustomProperties` 指定需要保留的变量。
#### 示例
```css
// 原始输出
page,
:root {
--spacing: 8rpx;
}
.h-2 {
height: calc(var(--spacing) * 2);
}
```
```css
// 启用 cssCalc 后
.h-2 {
height: 16rpx;
height: calc(var(--spacing) * 2);
}
```
```js
cssCalc: ['--spacing']
cssCalc: { includeCustomProperties: ['--spacing'] }
```
### injectAdditionalCssVarScope
> 可选 | 类型: `boolean` | 默认值: `false` | 版本: ^2.6.0
是否额外注入 `tailwindcss css var scope`。
#### 备注
当构建链路(例如 `@tarojs/plugin-html`)移除了包含 `*` 的选择器时,可启用该选项重新写入变量作用域,以避免渐变等功能失效。
#### 默认值
```ts
false
```
### rewriteCssImports
> 可选 | 类型: `boolean` | 默认值: `true`
是否在 webpack/vite 阶段自动把 CSS 中的 `@import 'tailwindcss'` 映射为 `weapp-tailwindcss/index.css`。
#### 备注
开启后打包链路只会在处理样式时拦截 `tailwindcss` 的导入路径(JS/TS `import 'tailwindcss'` 不会被修改),让源码可以继续写 `@import 'tailwindcss';`,同时输出 `weapp-tailwindcss/index.css` 的样式。传入 `false` 可完全关闭该行为。
#### 默认值
```ts
true
```
### cssSelectorReplacement
> 可选 | 类型: `{ root?: string | string[] | false; universal?: string | string[] | false; }` | 默认值: 详见下方
控制 CSS 选择器的替换规则。
#### 默认值
`ts 'page'` |
| `universal?` | `string` \| `false` | **`Default`** `ts 'view'` |
### rem2rpx
> 可选 | 类型: `boolean | Rem2rpxOptions` | 版本: ^3.0.0
rem 到 rpx 的转换配置。
#### 备注
传入 `true` 使用默认配置,或提供 [postcss-rem-to-responsive-pixel](https://www.npmjs.com/package/postcss-rem-to-responsive-pixel) 支持的完整选项。
```ts
{
rootValue: 32,
propList: ['*'],
transformUnit: 'rpx',
}
```
### px2rpx
> 可选 | 类型: `boolean | Px2rpxOptions` | 版本: ^4.3.0
px 到 rpx 的转换配置。
#### 备注
传入 `true` 启用默认映射(`1px = 1rpx`),或通过对象自定义更多行为。
### unitsToPx
> 可选 | 类型: `boolean | UnitsToPxOptions`
多单位转 px 的转换配置。
#### 备注
传入 `true` 启用默认映射(postcss-units-to-px 默认单位表),或通过对象自定义行为。
默认关闭。
### cssPresetEnv
> 可选 | 类型: `PresetEnvOptions` | 版本: ^4.0.0
`postcss-preset-env` 的配置项。
#### 参阅
- ://preset-env.cssdb.org/
- ://github.com/csstools/postcss-plugins/tree/main/plugin-packs/postcss-preset-env#readme
### tailwindcss
> 可选 | 类型: `import("/Users/yangqiming/Documents/GitHub/weapp-tailwindcss/packages/weapp-tailwindcss/src/typedoc.export").TailwindCssOptions` | 版本: ^4.0.0
为不同版本的 Tailwind 配置行为。
### cssEntries
> 可选 | 类型: `string[]` | 版本: ^4.2.6
指定 tailwindcss@4 的入口 CSS。
#### 备注
未配置时无法加载自定义插件,等价于设置 `tailwindcss.v4.cssEntries`。
---
## 🧭 生命周期
本页收录 4 个配置项,来源于 `UserDefinedOptions`。
## 配置一览
| 配置项 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| [onLoad](#onload) | (() => void) | — | 插件 `apply` 初始调用时触发。 |
| [onStart](#onstart) | (() => void) | — | 开始处理前触发。 |
| [onUpdate](#onupdate) | (filename: string, oldVal: string, newVal: string) => void | — | 匹配并修改文件后触发。 |
| [onEnd](#onend) | (() => void) | — | 结束处理时触发。 |
## 详细说明
### onLoad
> 可选 | 类型: `(() => void)`
插件 `apply` 初始调用时触发。
#### 返回
`void`
### onStart
> 可选 | 类型: `(() => void)`
开始处理前触发。
#### 返回
`void`
### onUpdate
> 可选 | 类型: `(filename: string, oldVal: string, newVal: string) => void`
匹配并修改文件后触发。
#### 参数
##### filename
`string`
##### oldVal
`string`
##### newVal
`string`
#### 返回
`void`
### onEnd
> 可选 | 类型: `(() => void)`
结束处理时触发。
#### 返回
`void`
---
## 🧩 文件匹配
本页收录 6 个配置项,来源于 `UserDefinedOptions`。
## 配置一览
| 配置项 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| [htmlMatcher](#htmlmatcher) | (name: string) => boolean | — | 匹配需要处理的 `wxml` 等模板文件。 |
| [cssMatcher](#cssmatcher) | (name: string) => boolean | — | 匹配需要处理的 `wxss` 等样式文件。 |
| [jsMatcher](#jsmatcher) | (name: string) => boolean | — | 匹配需要处理的编译后 `js` 文件。 |
| [mainCssChunkMatcher](#maincsschunkmatcher) | (name: string, appType?: AppType) => boolean | — | 匹配负责注入 Tailwind CSS 变量作用域的 CSS Bundle。 |
| [wxsMatcher](#wxsmatcher) | (name: string) => boolean | ()=>false | 匹配各端的 `wxs`/`sjs`/`.filter.js` 文件。 |
| [inlineWxs](#inlinewxs) | boolean | false | 是否转义 `wxml` 中的内联 `wxs`。 |
## 详细说明
### htmlMatcher
> 可选 | 类型: `(name: string) => boolean`
匹配需要处理的 `wxml` 等模板文件。
#### 参数
##### name
`string`
#### 返回
`boolean`
### cssMatcher
> 可选 | 类型: `(name: string) => boolean`
匹配需要处理的 `wxss` 等样式文件。
#### 参数
##### name
`string`
#### 返回
`boolean`
### jsMatcher
> 可选 | 类型: `(name: string) => boolean`
匹配需要处理的编译后 `js` 文件。
#### 参数
##### name
`string`
#### 返回
`boolean`
### mainCssChunkMatcher
> 可选 | 类型: `(name: string, appType?: AppType) => boolean`
匹配负责注入 Tailwind CSS 变量作用域的 CSS Bundle。
#### 备注
在处理 `::before`/`::after` 等不兼容选择器时,建议手动指定文件位置。
#### 参数
##### name
`string`
##### appType?
`AppType`
#### 返回
`boolean`
### wxsMatcher
> 可选 | 类型: `(name: string) => boolean` | 默认值: `()=>false`
匹配各端的 `wxs`/`sjs`/`.filter.js` 文件。
#### 备注
配置前请确保在 `tailwind.config.js` 的 `content` 中包含对应格式。
#### 默认值
```ts
()=>false
```
#### 参数
##### name
`string`
#### 返回
`boolean`
### inlineWxs
> 可选 | 类型: `boolean` | 默认值: `false`
是否转义 `wxml` 中的内联 `wxs`。
#### 备注
使用前同样需要在 `tailwind.config.js` 中声明 `wxs` 格式。
#### 默认值
```ts
false
```
#### 示例
```html
// 我是内联wxs
// 下方的类名会被转义
var className = "after:content-['我是className']"
module.exports = {
className: className
}
```
---
## 🗂️ 其他接口
以下接口用于补充配置或运行时能力,本页面仅提供索引。
- [ApplyOptions](./interfaces/ApplyOptions.md) - Preferred options for runtime patch behavior.
- [CacheOptions](./interfaces/CacheOptions.md) - Configures how the Tailwind class cache is stored and where it lives on disk.
- [DisabledOptions](./interfaces/DisabledOptions.md) - 禁用插件功能的细粒度选项。
- [ExtractOptions](./interfaces/ExtractOptions.md) - Preferred options for extraction output behavior.
- [TailwindCssOptions](./interfaces/TailwindCssOptions.md) - High-level Tailwind patch configuration shared across versions.
- [TailwindCssPatchOptions](./interfaces/TailwindCssPatchOptions.md) - Root configuration consumed by the Tailwind CSS patch runner.
- [TailwindV2Options](./interfaces/TailwindV2Options.md) - Configuration specific to Tailwind CSS v2 patching flows.
- [TailwindV3Options](./interfaces/TailwindV3Options.md) - Configuration specific to Tailwind CSS v3 patching flows.
- [TailwindV4Options](./interfaces/TailwindV4Options.md) - Additional configuration specific to Tailwind CSS v4 extraction.
---
## Class: UnifiedWebpackPluginV5
**`Name`**
UnifiedWebpackPluginV5
**`Description`**
webpack5 核心转义插件
**`Link`**
https://tw.icebreaker.top/docs/intro
## Implements
- [`IBaseWebpackPlugin`](../interfaces/IBaseWebpackPlugin.md)
## Constructors
### constructor
• **new UnifiedWebpackPluginV5**(`options?`): [`UnifiedWebpackPluginV5`](UnifiedWebpackPluginV5.md)
#### Parameters
| Name | Type |
| :-------- | :---------------------------------------------------------- |
| `options` | [`UserDefinedOptions`](../interfaces/UserDefinedOptions.md) |
#### Returns
[`UnifiedWebpackPluginV5`](UnifiedWebpackPluginV5.md)
#### Defined in
[webpack/BaseUnifiedPlugin/v5.ts:24](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/webpack/BaseUnifiedPlugin/v5.ts#L24)
## Properties
### appType
• `Optional` **appType**: [`AppType`](../#apptype)
#### Implementation of
[IBaseWebpackPlugin](../interfaces/IBaseWebpackPlugin.md).[appType](../interfaces/IBaseWebpackPlugin.md#apptype)
#### Defined in
[webpack/BaseUnifiedPlugin/v5.ts:22](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/webpack/BaseUnifiedPlugin/v5.ts#L22)
---
### options
• **options**: `Required`<`Omit`<[`UserDefinedOptions`](../interfaces/UserDefinedOptions.md), `"customReplaceDictionary"` \| `"supportCustomLengthUnitsPatch"` \| [`GlobOrFunctionMatchers`](../#globorfunctionmatchers)\> & \{ `cssMatcher`: (`name`: `string`) => `boolean` ; `htmlMatcher`: (`name`: `string`) => `boolean` ; `jsMatcher`: (`name`: `string`) => `boolean` ; `mainCssChunkMatcher`: (`name`: `string`, `appType?`: [`AppType`](../#apptype)) => `boolean` ; `wxsMatcher`: (`name`: `string`) => `boolean` } & \{ `cache`: `ICreateCacheReturnType` ; `customReplaceDictionary`: `Record`<`string`, `string`\> ; `escapeMap`: `Record`<`string`, `string`\> ; `jsHandler`: [`JsHandler`](../#jshandler) ; `patch`: () => `void` ; `setMangleRuntimeSet`: (`runtimeSet`: `Set`<`string`\>) => `void` ; `styleHandler`: (`rawSource`: `string`, `options`: [`IStyleHandlerOptions`](../#istylehandleroptions)) => `Promise`<`string`\> ; `supportCustomLengthUnitsPatch`: `false` \| [`ILengthUnitsPatchOptions`](../interfaces/ILengthUnitsPatchOptions.md) ; `templateHandler`: (`rawSource`: `string`, `options?`: [`ITemplateHandlerOptions`](../interfaces/ITemplateHandlerOptions.md)) => `string` }\>
#### Implementation of
[IBaseWebpackPlugin](../interfaces/IBaseWebpackPlugin.md).[options](../interfaces/IBaseWebpackPlugin.md#options)
#### Defined in
[webpack/BaseUnifiedPlugin/v5.ts:21](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/webpack/BaseUnifiedPlugin/v5.ts#L21)
## Methods
### apply
▸ **apply**(`compiler`): `void`
#### Parameters
| Name | Type |
| :--------- | :--------- |
| `compiler` | `Compiler` |
#### Returns
`void`
#### Implementation of
[IBaseWebpackPlugin](../interfaces/IBaseWebpackPlugin.md).[apply](../interfaces/IBaseWebpackPlugin.md#apply)
#### Defined in
[webpack/BaseUnifiedPlugin/v5.ts:32](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/webpack/BaseUnifiedPlugin/v5.ts#L32)
---
## weapp-tailwindcss-webpack-plugin
## Classes
- [UnifiedWebpackPluginV5](classes/UnifiedWebpackPluginV5.md)
## Interfaces
- [IArbitraryValues](interfaces/IArbitraryValues.md)
- [IBaseWebpackPlugin](interfaces/IBaseWebpackPlugin.md)
- [ICommonReplaceOptions](interfaces/ICommonReplaceOptions.md)
- [ILengthUnitsPatchDangerousOptions](interfaces/ILengthUnitsPatchDangerousOptions.md)
- [ILengthUnitsPatchOptions](interfaces/ILengthUnitsPatchOptions.md)
- [IPropValue](interfaces/IPropValue.md)
- [ITemplateHandlerOptions](interfaces/ITemplateHandlerOptions.md)
- [InternalCssSelectorReplacerOptions](interfaces/InternalCssSelectorReplacerOptions.md)
- [InternalPatchResult](interfaces/InternalPatchResult.md)
- [RawSource](interfaces/RawSource.md)
- [UserDefinedOptions](interfaces/UserDefinedOptions.md)
## Type Aliases
### AppType
Ƭ **AppType**: `"uni-app"` \| `"uni-app-vite"` \| `"taro"` \| `"remax"` \| `"rax"` \| `"native"` \| `"kbone"` \| `"mpx"`
#### Defined in
[types.ts:10](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L10)
---
### CreateJsHandlerOptions
Ƭ **CreateJsHandlerOptions**: `Omit`<[`IJsHandlerOptions`](#ijshandleroptions), `"classNameSet"`\>
#### Defined in
[types.ts:502](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L502)
---
### CssPreflightOptions
Ƭ **CssPreflightOptions**: \{ `[key: CssPresetProps]`: `string` \| `number` \| `boolean`; } \| `false`
#### Defined in
[types.ts:19](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L19)
---
### CssPresetProps
Ƭ **CssPresetProps**: `string`
#### Defined in
[types.ts:17](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L17)
### GlobOrFunctionMatchers
Ƭ **GlobOrFunctionMatchers**: `"htmlMatcher"` \| `"cssMatcher"` \| `"jsMatcher"` \| `"mainCssChunkMatcher"` \| `"wxsMatcher"`
#### Defined in
[types.ts:460](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L460)
---
### ICustomAttributes
Ƭ **ICustomAttributes**: `Record`<`string`, [`ItemOrItemArray`](#itemoritemarray)<`string` \| `RegExp`\>\> \| `Map`<`string` \| `RegExp`, [`ItemOrItemArray`](#itemoritemarray)<`string` \| `RegExp`\>\>
#### Defined in
[types.ts:50](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L50)
---
### ICustomAttributesEntities
Ƭ **ICustomAttributesEntities**: [`string` \| `RegExp`, [`ItemOrItemArray`](#itemoritemarray)<`string` \| `RegExp`\>][]
#### Defined in
[types.ts:52](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L52)
---
### IJsHandlerOptions
Ƭ **IJsHandlerOptions**: `Object`
#### Type declaration
| Name | Type |
| :----------------- | :------------------------------------------------------------------------------- |
| `arbitraryValues?` | [`IArbitraryValues`](interfaces/IArbitraryValues.md) |
| `classNameSet` | `Set`<`string`\> |
| `escapeMap?` | `Record`<`string`, `string`\> |
| `generateMap?` | `boolean` |
| `jsPreserveClass?` | (`keyword`: `string`) => `boolean` \| `undefined` |
| `minifiedJs?` | `boolean` |
| `needEscaped?` | `boolean` |
| `strategy?` | [`UserDefinedOptions`](interfaces/UserDefinedOptions.md)[``"jsEscapeStrategy"``] |
#### Defined in
[types.ts:54](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L54)
---
### IStyleHandlerOptions
Ƭ **IStyleHandlerOptions**: [`RequiredStyleHandlerOptions`](#requiredstylehandleroptions) & \{ `ctx?`: `IContext` ; `postcssOptions?`: [`LoadedPostcssOptions`](#loadedpostcssoptions) ; `cssRemoveProperty?`: `boolean` ; `cssRemoveHoverPseudoClass?`: `boolean` ; `cssPresetEnv?`: [`PresetEnvOptions`](#presetenvoptions) ; `cssCalc?`: `boolean` \| [`CssCalcOptions`](#csscalcoptions) \| (`string` \| `RegExp`)[] ; `atRules?`: \{ `property?`: `boolean` ; `supports?`: `boolean` ; `media?`: `boolean` } ; `uniAppX?`: `boolean` ; `majorVersion?`: `number` }
#### Defined in
[types.ts:41](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L41)
---
### InternalPostcssOptions
Ƭ **InternalPostcssOptions**: `Pick`<[`UserDefinedOptions`](interfaces/UserDefinedOptions.md), `"cssMatcher"` \| `"mainCssChunkMatcher"` \| `"cssPreflight"` \| `"replaceUniversalSelectorWith"` \| `"cssPreflightRange"` \| `"disabled"`\>
#### Defined in
[types.ts:479](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L479)
---
### InternalUserDefinedOptions
Ƭ **InternalUserDefinedOptions**: `Required`<`Omit`<[`UserDefinedOptions`](interfaces/UserDefinedOptions.md), [`GlobOrFunctionMatchers`](#globorfunctionmatchers) \| `"supportCustomLengthUnitsPatch"` \| `"customReplaceDictionary"`\> & \{ [K in GlobOrFunctionMatchers]: K extends "mainCssChunkMatcher" ? Function : Function } & \{ `cache`: `ICreateCacheReturnType` ; `customReplaceDictionary`: `Record`<`string`, `string`\> ; `escapeMap`: `Record`<`string`, `string`\> ; `jsHandler`: [`JsHandler`](#jshandler) ; `patch`: () => `void` ; `setMangleRuntimeSet`: (`runtimeSet`: `Set`<`string`\>) => `void` ; `styleHandler`: (`rawSource`: `string`, `options`: [`IStyleHandlerOptions`](#istylehandleroptions)) => `Promise`<`string`\> ; `supportCustomLengthUnitsPatch`: [`ILengthUnitsPatchOptions`](interfaces/ILengthUnitsPatchOptions.md) \| `false` ; `templateHandler`: (`rawSource`: `string`, `options?`: [`ITemplateHandlerOptions`](interfaces/ITemplateHandlerOptions.md)) => `string` }\>
#### Defined in
[types.ts:462](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L462)
---
### ItemOrItemArray
Ƭ **ItemOrItemArray**<`T`\>: `T` \| `T`[]
#### Type parameters
| Name |
| :--- |
| `T` |
#### Defined in
[types.ts:8](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L8)
---
### JsHandler
Ƭ **JsHandler**: (`rawSource`: `string`, `set`: `Set`<`string`\>, `options?`: [`CreateJsHandlerOptions`](#createjshandleroptions)) => [`JsHandlerResult`](#jshandlerresult)
#### Type declaration
▸ (`rawSource`, `set`, `options?`): [`JsHandlerResult`](#jshandlerresult)
##### Parameters
| Name | Type |
| :---------- | :-------------------------------------------------- |
| `rawSource` | `string` |
| `set` | `Set`<`string`\> |
| `options?` | [`CreateJsHandlerOptions`](#createjshandleroptions) |
##### Returns
[`JsHandlerResult`](#jshandlerresult)
#### Defined in
[types.ts:428](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L428)
---
### JsHandlerReplaceResult
Ƭ **JsHandlerReplaceResult**: `Object`
#### Type declaration
| Name | Type |
| :----- | :---------- |
| `code` | `string` |
| `map?` | `SourceMap` |
#### Defined in
[types.ts:46](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L46)
---
### JsHandlerResult
Ƭ **JsHandlerResult**: [`JsHandlerReplaceResult`](#jshandlerreplaceresult) \| `GeneratorResult`
#### Defined in
[types.ts:48](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L48)
---
### RequiredStyleHandlerOptions
Ƭ **RequiredStyleHandlerOptions**: \{ `cssInjectPreflight?`: `InjectPreflight` ; `escapeMap?`: `Record`<`string`, `string`\> ; `isMainChunk`: `boolean` } & `Pick`<[`UserDefinedOptions`](interfaces/UserDefinedOptions.md), `"cssPreflightRange"` \| `"cssChildCombinatorReplaceValue"` \| `"replaceUniversalSelectorWith"` \| `"injectAdditionalCssVarScope"` \| `"cssSelectorReplacement"`\>
#### Defined in
[types.ts:25](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L25)
### LoadedPostcssOptions
`LoadedPostcssOptions` 是 `postcss-load-config` 导出的 `Result` 类型去掉 `file` 字段后再取 `Partial`。在插件内部用于接收已经过 `postcss-load-config` 解析的运行时配置,例如自定义插件、语法语义等设置。
#### 定义
```ts
type LoadedPostcssOptions = Partial>
```
#### 定义于
[packages/postcss/src/types.ts:14](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/packages/postcss/src/types.ts#L14)
### PresetEnvOptions
`PresetEnvOptions` 直接复用自 `postcss-preset-env` 的 `pluginOptions`,用于控制 `stage`、`browsers`、`features` 等行为。传入该类型可以在保持 Docusaurus 生成文档一致的同时,自由扩展 CSS 预处理特性。
#### 定义
```ts
```
#### 定义于
[packages/postcss/src/types.ts:8](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/packages/postcss/src/types.ts#L8)
### CssCalcOptions
`CssCalcOptions` 基于 `@weapp-tailwindcss/postcss-calc` 的 `PostCssCalcOptions` 扩展而来,并额外提供 `includeCustomProperties`,用于声明哪些自定义属性需要参与 `calc` 计算或在输出中保留。
#### 定义
```ts
interface CssCalcOptions extends PostCssCalcOptions {
includeCustomProperties?: (string | RegExp)[]
}
```
#### 定义于
[packages/postcss/src/types.ts:45](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/packages/postcss/src/types.ts#L45)
## Functions
### UnifiedViteWeappTailwindcssPlugin
▸ **UnifiedViteWeappTailwindcssPlugin**(`options?`): `Plugin` \| `undefined`
#### Parameters
| Name | Type |
| :-------- | :------------------------------------------------------- |
| `options` | [`UserDefinedOptions`](interfaces/UserDefinedOptions.md) |
#### Returns
`Plugin` \| `undefined`
**`Name`**
UnifiedViteWeappTailwindcssPlugin
**`Description`**
uni-app vite vue3 版本插件
**`Link`**
https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
#### Defined in
[vite/index.ts:17](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/vite/index.ts#L17)
---
### createPlugins
▸ **createPlugins**(`options?`): `Object`
#### Parameters
| Name | Type |
| :-------- | :------------------------------------------------------- |
| `options` | [`UserDefinedOptions`](interfaces/UserDefinedOptions.md) |
#### Returns
`Object`
| Name | Type |
| :-------------- | :---------------- |
| `transformJs` | () => `Transform` |
| `transformWxml` | () => `Transform` |
| `transformWxss` | () => `Transform` |
**`Name`**
weapp-tw-gulp
**`Description`**
gulp版本weapp-tw插件
**`Link`**
https://tw.icebreaker.top/docs/quick-start/frameworks/native
#### Defined in
[gulp/index.ts:17](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/gulp/index.ts#L17)
---
## Interface: IArbitraryValues
## Properties
### allowDoubleQuotes
• `Optional` **allowDoubleQuotes**: `boolean`
是否允许在类名里,使用双引号。
建议不要开启,因为有些框架,比如 `vue3` 它针对有些静态模板会直接编译成 `html` 字符串,此时开启这个配置很有可能导致转义出错
**`Example`**
```html
```
**`Default`**
`false`
#### Defined in
[types.ts:114](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L114)
---
## Interface: IBaseWebpackPlugin
## Implemented by
- [`UnifiedWebpackPluginV5`](../classes/UnifiedWebpackPluginV5.md)
## Properties
### appType
• `Optional` **appType**: [`AppType`](../#apptype)
#### Defined in
[types.ts:488](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L488)
---
### apply
• **apply**: (`compiler`: `any`) => `void`
#### Type declaration
▸ (`compiler`): `void`
##### Parameters
| Name | Type |
| :--------- | :---- |
| `compiler` | `any` |
##### Returns
`void`
#### Defined in
[types.ts:490](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L490)
---
### options
• **options**: `Required`<`Omit`<[`UserDefinedOptions`](UserDefinedOptions.md), `"customReplaceDictionary"` \| `"supportCustomLengthUnitsPatch"` \| [`GlobOrFunctionMatchers`](../#globorfunctionmatchers)\> & \{ `cssMatcher`: (`name`: `string`) => `boolean` ; `htmlMatcher`: (`name`: `string`) => `boolean` ; `jsMatcher`: (`name`: `string`) => `boolean` ; `mainCssChunkMatcher`: (`name`: `string`, `appType?`: [`AppType`](../#apptype)) => `boolean` ; `wxsMatcher`: (`name`: `string`) => `boolean` } & \{ `cache`: `ICreateCacheReturnType` ; `customReplaceDictionary`: `Record`<`string`, `string`\> ; `escapeMap`: `Record`<`string`, `string`\> ; `jsHandler`: [`JsHandler`](../#jshandler) ; `patch`: () => `void` ; `setMangleRuntimeSet`: (`runtimeSet`: `Set`<`string`\>) => `void` ; `styleHandler`: (`rawSource`: `string`, `options`: [`IStyleHandlerOptions`](../#istylehandleroptions)) => `Promise`<`string`\> ; `supportCustomLengthUnitsPatch`: `false` \| [`ILengthUnitsPatchOptions`](ILengthUnitsPatchOptions.md) ; `templateHandler`: (`rawSource`: `string`, `options?`: [`ITemplateHandlerOptions`](ITemplateHandlerOptions.md)) => `string` }\>
#### Defined in
[types.ts:487](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L487)
---
## Interface: ICommonReplaceOptions
## Hierarchy
- **`ICommonReplaceOptions`**
↳ [`ITemplateHandlerOptions`](ITemplateHandlerOptions.md)
## Properties
### escapeMap
• `Optional` **escapeMap**: `Record`<`string`, `string`\>
#### Defined in
[types.ts:442](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L442)
---
### keepEOL
• `Optional` **keepEOL**: `boolean`
#### Defined in
[types.ts:441](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L441)
---
## Interface: ILengthUnitsPatchDangerousOptions
## Properties
### destPath
• `Optional` **destPath**: `string`
#### Defined in
[types.ts:81](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L81)
---
### gteVersion
• `Optional` **gteVersion**: `string`
#### Defined in
[types.ts:77](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L77)
---
### lengthUnitsFilePath
• `Optional` **lengthUnitsFilePath**: `string`
#### Defined in
[types.ts:78](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L78)
---
### overwrite
• `Optional` **overwrite**: `boolean`
#### Defined in
[types.ts:80](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L80)
---
### packageName
• `Optional` **packageName**: `string`
#### Defined in
[types.ts:76](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L76)
---
### variableName
• `Optional` **variableName**: `string`
#### Defined in
[types.ts:79](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L79)
---
## Interface: ILengthUnitsPatchOptions
**`Deprecated`**
## Properties
### basedir
• `Optional` **basedir**: `string`
#### Defined in
[types.ts:91](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L91)
---
### dangerousOptions
• `Optional` **dangerousOptions**: [`ILengthUnitsPatchDangerousOptions`](ILengthUnitsPatchDangerousOptions.md)
#### Defined in
[types.ts:90](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L90)
---
### paths
• `Optional` **paths**: `string`[]
#### Defined in
[types.ts:89](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L89)
---
### units
• **units**: `string`[]
#### Defined in
[types.ts:88](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L88)
---
## Interface: IPropValue
## Properties
### prop
• **prop**: `string`
#### Defined in
[types.ts:13](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L13)
---
### value
• **value**: `string`
#### Defined in
[types.ts:14](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L14)
---
## Interface: ITemplateHandlerOptions
## Hierarchy
- [`ICommonReplaceOptions`](ICommonReplaceOptions.md)
↳ **`ITemplateHandlerOptions`**
## Properties
### customAttributesEntities
• `Optional` **customAttributesEntities**: [`ICustomAttributesEntities`](../#icustomattributesentities)
#### Defined in
[types.ts:447](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L447)
---
### disabledDefaultTemplateHandler
• `Optional` **disabledDefaultTemplateHandler**: `boolean`
#### Defined in
[types.ts:456](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L456)
---
### escapeMap
• `Optional` **escapeMap**: `Record`<`string`, `string`\>
#### Overrides
[ICommonReplaceOptions](ICommonReplaceOptions.md).[escapeMap](ICommonReplaceOptions.md#escapemap)
#### Defined in
[types.ts:451](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L451)
---
### inlineWxs
• `Optional` **inlineWxs**: `boolean`
#### Defined in
[types.ts:453](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L453)
---
### jsHandler
• `Optional` **jsHandler**: [`JsHandler`](../#jshandler)
#### Defined in
[types.ts:454](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L454)
---
### keepEOL
• `Optional` **keepEOL**: `boolean`
#### Inherited from
[ICommonReplaceOptions](ICommonReplaceOptions.md).[keepEOL](ICommonReplaceOptions.md#keepeol)
#### Defined in
[types.ts:441](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L441)
### quote
• `Optional` **quote**: `null` \| `string`
#### Defined in
[types.ts:457](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L457)
---
### runtimeSet
• `Optional` **runtimeSet**: `Set`<`string`\>
#### Defined in
[types.ts:455](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L455)
---
## Interface: InternalCssSelectorReplacerOptions
## Properties
### escapeMap
• `Optional` **escapeMap**: `Record`<`string`, `string`\>
#### Defined in
[types.ts:38](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L38)
---
## Interface: InternalPatchResult
**`Description`**
InternalPatchResult
## Properties
### dataTypes
• `Optional` **dataTypes**: `string`
#### Defined in
[types.ts:497](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L497)
---
### plugin
• `Optional` **plugin**: `string`
#### Defined in
[types.ts:499](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L499)
---
### processTailwindFeatures
• `Optional` **processTailwindFeatures**: `string`
#### Defined in
[types.ts:498](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L498)
---
## Interface: RawSource
## Properties
### end
• **end**: `number`
#### Defined in
[types.ts:67](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L67)
---
### raw
• **raw**: `string`
#### Defined in
[types.ts:68](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L68)
---
### source
• `Optional` **source**: `string`
#### Defined in
[types.ts:70](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L70)
---
### start
• **start**: `number`
#### Defined in
[types.ts:66](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L66)
---
## Interface: UserDefinedOptions
## Properties
### appType
• `Optional` **appType**: [`AppType`](../#apptype)
**`Description`**
使用的框架类型(uni-app,taro...),用于找到主要的 `css bundle` 进行转化,这个配置会影响默认方法 `mainCssChunkMatcher` 的行为,不传会去猜测 `tailwindcss css var inject scope` 的位置
#### Defined in
[types.ts:284](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L284)
---
### arbitraryValues
• `Optional` **arbitraryValues**: [`IArbitraryValues`](IArbitraryValues.md)
**`Description`**
针对 tailwindcss arbitrary values 的一些配置
#### Defined in
[types.ts:301](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L301)
---
### cssChildCombinatorReplaceValue
• `Optional` **cssChildCombinatorReplaceValue**: `string` \| `string`[]
**`Description`**
用于控制 tailwindcss 子组合器的生效标签范围, 这里我们用一个例子来说明这个配置是干啥用的.
我们布局的时候往往会使用 `space-x-4`
那么实际上会生成这样的css选择器:
```css
.space-x-4>:not([hidden])~:not([hidden]){}
```
然而很不幸,这个选择器在小程序中是不支持的,写了会报错导致编译失败。
所以出于保守起见,我把它替换为了:
```css
.space-x-4>view + view{}
```
这同时也是默认值, 而这个选项就允许你进行自定义子组合器的行为
你可以传入一个 字符串,或者字符串数组
1. 传入字符串数组,比如 `['view','text']` 生成:
```css
.space-y-4>view + view,text + text{}
```
2. 传入一个字符串,此时行为变成了整个替换,比如 `'view,text,button,input ~ view,text,button,input'` 生成:
```css
.space-y-4>view,text,button,input ~ view,text,button,input{}
```
**`Default`**
```ts
'view + view'
```
#### Defined in
[types.ts:329](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L329)
---
### cssMatcher
• `Optional` **cssMatcher**: `string` \| `string`[] \| (`name`: `string`) => `boolean`
**`Description`**
匹配 `wxss` 等等样式文件的方法,支持 `glob` by [micromatch](https://github.com/micromatch/micromatch)
#### Defined in
[types.ts:125](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L125)
---
### cssPreflight
• `Optional` **cssPreflight**: [`CssPreflightOptions`](../#csspreflightoptions)
**`Issue`**
**`Description`**
在所有 view节点添加的 css 预设,可根据情况自由的禁用原先的规则,或者添加新的规则。 详细用法如下:
```js
// default 默认:
cssPreflight: {
'box-sizing': 'border-box',
'border-width': '0',
'border-style': 'solid',
'border-color': 'currentColor'
}
// result
// box-sizing: border-box;
// border-width: 0;
// border-style: solid;
// border-color: currentColor
// case 禁用所有
cssPreflight: false
// result
// none
// case 禁用单个属性
cssPreflight: {
'box-sizing': false
}
// border-width: 0;
// border-style: solid;
// border-color: currentColor
// case 更改和添加单个属性
cssPreflight: {
'box-sizing': 'content-box',
'background': 'black'
}
// result
// box-sizing: content-box;
// border-width: 0;
// border-style: solid;
// border-color: currentColor;
// background: black
```
#### Defined in
[types.ts:178](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L178)
---
### cssPreflightRange
• `Optional` **cssPreflightRange**: `"view"` \| `"all"`
**`Issue`**
**`Description`**
全局`dom`选择器,只有在这个选择器作用范围内的`dom`会被注入 `cssPreflight` 的变量和默认样式。默认为 `'view'` 即只对所有的 `view` 和伪元素生效,想要对所有的元素生效,可切换为 `'all'`,此时需要自行处理和客户端默认样式的冲突
#### Defined in
[types.ts:184](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L184)
---
### cssSelectorReplacement
• `Optional` **cssSelectorReplacement**: `Object`
#### Type declaration
| Name | Type | Description |
| :----------- | :------------------ | :------------------------ |
| `root?` | `string` \| `false` | **`Default`** `ts 'page'` |
| `universal?` | `string` \| `false` | **`Default`** `ts 'view'` |
#### Defined in
[types.ts:410](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L410)
---
### customAttributes
• `Optional` **customAttributes**: [`ICustomAttributes`](../#icustomattributes)
**`Description`**
**这是一个重要的配置!**
它可以自定义`wxml`标签上的`attr`转化属性。默认转化所有的`class`和`hover-class`,这个`Map`的 `key`为匹配标签,`value`为属性字符串或者匹配正则数组。
如果你想要增加,对于所有标签都生效的转化的属性,你可以添加 `*`: `(string | Regexp)[]` 这样的键值对。(`*` 是一个特殊值,代表所有标签)
更复杂的情况,可以传一个 `Map`实例。
假如你要把 `className` 通过组件的`prop`传递给子组件,又或者想要自定义转化的标签属性时,需要用到此配置,案例详见:[issue#129](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/129#issuecomment-1340914688),[issue#134](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/134#issuecomment-1351288238)
**`Example`**
```js
const customAttributes = {
// 匹配所有带 Class / class 相关的标签,比如 `a-class`, `testClass` , `custom-class` 里的值
'*': [ /[A-Za-z]?[A-Za-z-]*[Cc]lass/ ],
// 额外匹配转化 `van-image` 标签上的 `custom-class` 的值
'van-image': ['custom-class'],
'ice-button': ['testClass']
}
```
当然你可以根据自己的需求,定义单个或者多个正则/字符串。
甚至有可能你编写正则表达式,它们匹配的范围,直接包括了插件里自带默认的 `class`/`hover-class`,那么这种情况下,你完全可以取代插件的默认模板转化器,开启 [disabledDefaultTemplateHandler](/docs/api/options/general#disableddefaulttemplatehandler) 配置项,禁用默认的模版匹配转化器。
#### Defined in
[types.ts:251](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L251)
---
### customReplaceDictionary
• `Optional` **customReplaceDictionary**: `Record`<`string`, `string`\> \| `"simple"` \| `"complex"`
**`Description`**
自定义转化class名称字典,这个配置项用来自定义转化`class`名称字典,你可以使用这个选项来简化生成的`class`
插件中内置了`'simple'`模式和`'complex'`模式:
- `'simple'`模式: 把小程序中不允许的字符串,转义为**相等长度**的代替字符串,这种情况不追求转化目标字符串的一比一绝对等价,即无法从生成结果,反推原先的`class`
- `'complex'`模式: 把小程序中不允许的字符串,转义为**更长**的代替字符串,这种情况转化前后的字符串是等价的,可以从结果进行反推,缺点就是会生成更长的 `class` 导致 `wxml`和`wxss`这类的体积增大
当然,你也可以自定义,传一个 `Record` 类型,只需保证转化后 css 中的 `class` 选择器,不会和自己定义的 `class` 产生冲突即可,示例见[dic.ts](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/blob/main/src/dic.ts)
**`Default`**
```ts
'simple'
```
#### Defined in
[types.ts:263](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L263)
### disabled
• `Optional` **disabled**: `boolean`
**`Description`**
是否禁用此插件,一般用于构建到多平台时使用
#### Defined in
[types.ts:196](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L196)
---
### disabledDefaultTemplateHandler
• `Optional` **disabledDefaultTemplateHandler**: `boolean`
**`Version`**
`^2.6.2`
**`Description`**
开启此选项,将会禁用默认 `wxml` 模板替换器,此时模板的匹配和转化将完全被 [`customAttributes`](/docs/api/options/important#customattributes) 接管,
此时你需要自己编写匹配之前默认 `class`/`hover-class`,以及新的标签属性的正则表达式`regex`
**`Default`**
```ts
false
```
#### Defined in
[types.ts:389](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L389)
---
### htmlMatcher
• `Optional` **htmlMatcher**: `string` \| `string`[] \| (`name`: `string`) => `boolean`
**`Description`**
匹配 `wxml`等等模板进行处理的方法,支持 `glob` by [micromatch](https://github.com/micromatch/micromatch)
#### Defined in
[types.ts:121](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L121)
---
### injectAdditionalCssVarScope
• `Optional` **injectAdditionalCssVarScope**: `boolean`
**`Version`**
`^2.6.0`
**`Description`**
是否注入额外的 `tailwindcss css var scope` 区域,这个选项用于这样的场景
比如 `taro vue3` 使用 [NutUI](https://nutui.jd.com), 需要使用 `@tarojs/plugin-html`,而这个插件会启用 `postcss-html-transform` 从而移除所有带 `*` 选择器
这会导致 `tailwindcss css var scope` 区域被移除导致一些样式,比如渐变等等功能失效
这种场景下,启用这个选项会再次重新注入整个 `tailwindcss css var scope`
**`Default`**
```ts
false
```
#### Defined in
[types.ts:373](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L373)
---
### inlineWxs
• `Optional` **inlineWxs**: `boolean`
**`Experiment`**
实验性质,有可能会改变
**`Description`**
是否转义 `wxml` 中内联的 `wxs`
> tip: 记得在 `tailwind.config.js` 中,把 `wxs` 这个格式加入 `content` 配置项,不然不会生效
**`Example`**
```html
// 我是内联wxs
// 下方的类名会被转义
var className = "after:content-['我是className']"
module.exports = {
className: className
}
```
**`Default`**
```ts
false
```
#### Defined in
[types.ts:359](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L359)
---
### jsEscapeStrategy
• `Optional` **jsEscapeStrategy**: `"regenerate"` \| `"replace"`
**`Version`**
`^2.7.0`
**`Description`**
js 字面量以及模板字符串的转义替换模式
- `regenerate` 模式,为需要转义的字面量,重新生成相同语义的字符串, (默认的传统模式)
- `replace` 模式,为在原版本字符串上直接精准替换, (`2.7.0+` 新增)
如果用一个比喻来形容,那么 `regenerate` 类似于创造一个双胞胎,而 `replace` 模式就类似于一把精准的手术刀
> `replace` 模式已经在 `2.8.0` 版本中,成为默认模式,另外使用这个模式之后,生成相关的参数,比如 `minifiedJs` 就会失效了。
**`Default`**
```ts
'regenerate'
```
#### Defined in
[types.ts:402](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L402)
---
### jsMatcher
• `Optional` **jsMatcher**: `string` \| `string`[] \| (`name`: `string`) => `boolean`
**`Description`**
匹配编译后 `js` 文件进行处理的方法,支持 `glob` by [micromatch](https://github.com/micromatch/micromatch)
#### Defined in
[types.ts:129](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L129)
---
### jsPreserveClass
• `Optional` **jsPreserveClass**: (`keyword`: `string`) => `undefined` \| `boolean`
#### Type declaration
▸ (`keyword`): `undefined` \| `boolean`
##### Parameters
| Name | Type |
| :-------- | :------- |
| `keyword` | `string` |
##### Returns
`undefined` \| `boolean`
**`Version`**
`^2.6.1`
**`Description`**
当 `tailwindcss` 和 `js` 处理的字面量撞车的时候,配置此选项可以用来保留js字面量,不进行转义处理。返回值中,想要当前js字面量保留,则返回 `true`。想要转义则返回 `false/undefined`
**`Default`**
保留所有带 `*` js字符串字面量
#### Defined in
[types.ts:380](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L380)
---
### mainCssChunkMatcher
• `Optional` **mainCssChunkMatcher**: `string` \| `string`[] \| (`name`: `string`, `appType?`: [`AppType`](../#apptype)) => `boolean`
**`Description`**
`tailwindcss css var inject scope` 的匹配方法,用于处理原始变量和替换不兼容选择器。可以不传,但是遇到某些 `::before/::after` 选择器注入冲突时,建议传入参数手动指定 css bundle 文件位置
#### Defined in
[types.ts:134](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L134)
### minifiedJs
• `Optional` **minifiedJs**: `boolean`
**`Description`**
是否压缩 js (`process.env.NODE_ENV` 为 `production` 时默认开启)
**`Default`**
```ts
process.env.NODE_ENV === 'production'
```
#### Defined in
[types.ts:290](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L290)
---
### onEnd
• `Optional` **onEnd**: () => `void`
#### Type declaration
▸ (): `void`
##### Returns
`void`
**`Description`**
结束处理时调用
#### Defined in
[types.ts:222](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L222)
---
### onLoad
• `Optional` **onLoad**: () => `void`
#### Type declaration
▸ (): `void`
##### Returns
`void`
**`Description`**
plugin apply 初调用
#### Defined in
[types.ts:206](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L206)
---
### onStart
• `Optional` **onStart**: () => `void`
#### Type declaration
▸ (): `void`
##### Returns
`void`
**`Description`**
开始处理时调用
#### Defined in
[types.ts:210](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L210)
---
### onUpdate
• `Optional` **onUpdate**: (`filename`: `string`, `oldVal`: `string`, `newVal`: `string`) => `void`
#### Type declaration
▸ (`filename`, `oldVal`, `newVal`): `void`
##### Parameters
| Name | Type |
| :--------- | :------- |
| `filename` | `string` |
| `oldVal` | `string` |
| `newVal` | `string` |
##### Returns
`void`
**`Description`**
匹配成功并修改文件内容后调用
#### Defined in
[types.ts:218](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L218)
---
### replaceUniversalSelectorWith
• `Optional` **replaceUniversalSelectorWith**: `string` \| `false`
**`Issue`**
**`Default`**
```ts
'view'
```
**`Description`**
把`css`中的全局选择器 **`*`** 替换为指定值,默认替换为 `'view'`,设置为 `false` 时不进行替换,此时小程序会由于不认识`*`选择器而报错
#### Defined in
[types.ts:191](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L191)
---
### supportCustomLengthUnitsPatch
• `Optional` **supportCustomLengthUnitsPatch**: `boolean` \| [`ILengthUnitsPatchOptions`](ILengthUnitsPatchOptions.md)
**`Deprecated`**
**`Issue`**
**`Description`**
自从`tailwindcss 3.2.0`对任意值添加了长度单位的校验后,小程序中的`rpx`这个`wxss`单位,由于不在长度合法名单中,于是被识别成了颜色,导致与预期不符,详见:[issues/110](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/110)。所以这个选项是用来给`tailwindcss`运行时,自动打上一个支持`rpx`单位的补丁。默认开启,在绝大部分情况下,你都可以忽略这个配置项,除非你需要更高级的自定义。
> 目前自动检索存在一定的缺陷,它会在第一次运行的时候不生效,关闭后第二次运行才生效。这是因为 nodejs 运行时先加载好了 `tailwindcss` 模块 ,然后再来运行这个插件,自动给 `tailwindcss` 运行时打上 `patch`。此时由于 `tailwindcss` 模块已经加载,所以 `patch` 在第一次运行时不生效,`ctrl+c` 关闭之后,再次运行才生效。这种情况可以使用:
```diff
"scripts": {
+ "postinstall": "weapp-tw patch"
}
```
使用 `npm hooks` 的方式来给 `tailwindcss` 自动打 `patch`
#### Defined in
[types.ts:279](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L279)
---
### tailwindcssBasedir
• `Optional` **tailwindcssBasedir**: `string`
**`Version`**
`^2.9.3`
**`Description`**
用于指定路径来获取 tailwindcss 上下文,一般情况下不用传入,使用 linked / monorepo 可能需要指定具体位置,路径通常是目标项目的 package.json 所在目录
#### Defined in
[types.ts:425](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L425)
---
### wxsMatcher
• `Optional` **wxsMatcher**: `string` \| `string`[] \| (`name`: `string`) => `boolean`
**`Experiment`**
实验性质,有可能会改变
**`Description`**
各个平台 `wxs` 文件的匹配方法,可以设置为包括微信的 .wxs,支付宝的 .sjs 和 百度小程序的 .filter.js
> tip: 记得在 `tailwind.config.js` 中,把 `wxs` 这个格式加入 `content` 配置项,不然不会生效
**`Default`**
```ts
()=>false
```
#### Defined in
[types.ts:337](https://github.com/sonofmagic/weapp-tailwindcss/blob/54db673b/src/types.ts#L337)
---
## css 中使用 @apply 警告问题
## 解决方案
我们以 `vscode` 为例
1. 创建 `.vscode` 目录
然后在目录下创建 `settings.json` 和 `tailwind.json`
2. 修改 `settings.json` 添加
```jsn
{
"css.customData": [".vscode/tailwind.json"]
}
```
3. 修改 `tailwind.json`
````json
{
"version": 1.1,
"atDirectives": [
{
"name": "@tailwind",
"description": "Use the `@tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#tailwind"
}
]
},
{
"name": "@apply",
"description": "Use the `@apply` directive to inline any existing utility classes into your own custom CSS. This is useful when you find a common utility pattern in your HTML that you’d like to extract to a new component.",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#apply"
}
]
},
{
"name": "@responsive",
"description": "You can generate responsive variants of your own classes by wrapping their definitions in the `@responsive` directive:\n```css\n@responsive {\n .alert {\n background-color: #E53E3E;\n }\n}\n```\n",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#responsive"
}
]
},
{
"name": "@screen",
"description": "The `@screen` directive allows you to create media queries that reference your breakpoints by **name** instead of duplicating their values in your own CSS:\n```css\n@screen sm {\n /* ... */\n}\n```\n…gets transformed into this:\n```css\n@media (min-width: 640px) {\n /* ... */\n}\n```\n",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#screen"
}
]
},
{
"name": "@variants",
"description": "Generate `hover`, `focus`, `active` and other **variants** of your own utilities by wrapping their definitions in the `@variants` directive:\n```css\n@variants hover, focus {\n .btn-brand {\n background-color: #3182CE;\n }\n}\n```\n",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#variants"
}
]
}
]
}
````
这样 `@apply` 就不会报错了。
## 参考文档
https://github.com/tailwindlabs/tailwindcss/discussions/5258
---
## 默认盒模型(box-sizing)问题
`Tailwindcss` 默认会把所有的元素的盒模型,设置为 `border-box`
但是一些组件库,比如 `wot-design-uni`,实现使用的是 `content-box` ,一切换到 `border-box` 高度塌陷了, 所以会导致部分显示效果错乱。
> `box-sizing: border-box;` 这行样式是在 'tailwindcss/base' 中的,所以你禁用这行代码,感觉上生效了,但是这样不是很好的解决方案。
假如你要从插件层面解决问题,只要做出如下修改:
```js
uvtw({
// 添加这一行配置即可
cssPreflight: {
'box-sizing': false,
},
}),
```
这样就可以把 `box-sizing` 这个样式给去掉,但是你这样就要去评估原先那些依赖盒模型的样式是否会受到影响:
比如 `w-2`, `h-4` 都是盒子模型潜在的影响。
## 参考文档
https://tw.icebreaker.top/docs/api/interfaces/UserDefinedOptions#csspreflight
https://github.com/sonofmagic/weapp-tailwindcss/issues/604
---
## CSS 变量失效问题
## 问题的现象
在使用 `taro` 或者 `uni-app` 中,可能你会遇到 `CSS` 变量失效问题
具体表现,就是你在使用下列类名的时候,小程序的模拟器上,不会出来任何的背景颜色:
```jsx
```
## 原因以及解决方案
导致这个的原因,是由于全局的 `tailwindcss` 变量丢失,没有注入进 `App` 引起的。参阅[什么是 `tailwindcss` 全局变量注入区域](#什么是全局-tailwindcss-变量注入区域)。
例如在 `taro` 中和 `@tarojs/plugin-html` 一起使用,就会出现这个问题,这是因为 `@tarojs/plugin-html` 把 `tailwindcss` 变量区域直接删除了。
遇到这样的问题,解决方案也很简单,只需要给插件传入 `injectAdditionalCssVarScope: true` 参数即可。
代码片段和配置详情详见[和 NutUI 一起使用](./use-with-nutui)。
## 设置成功后的效果
设置成功之后的效果如下所示,可以观察一下左侧的效果,和右下角的 `inspect` 面板作为参考

## 什么是全局 `tailwindcss` 变量注入区域
在你的 `app.wxss` 样式产物文件中(例如:`taro` 或 `uni-app` 的 `dist` 文件夹内),都有这样一块区域。
上面的这个问题,就是这块变量注入区域没了导致的。
```css
::before,::after {
--tw-content: "";
}
view,text,::before,::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
box-sizing: border-box;
border-width: 0;
border-style: solid;
border-color: currentColor;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
```
这块区域就是你 `@tailwind base;` 展开后, `tailwindcss` 注入的全局变量块。
丢失这块区域会导致 `bg-gradient-to-r` 这种依赖 `css` 变量的原子类失效。
---
## 组件外部样式类(externalClasses)的支持
:::warning 快速结论
如果在自定义组件里写了 `my-class="bg-[#fafa00] text-[40px]"`,但调试器里看到变成了 `my-class="bg- #fafa00 text- 40px"` 并导致样式失效,请在插件配置中为 `customAttributes` 显式声明 `my-class`。
:::
## 典型现象
在封装原生自定义组件时经常会用到外部样式类(`externalClasses`)。例如:
```js
/* custom-component.js */
Component({
externalClasses: ['my-class'],
})
```
在页面里直接使用 `tailwindcss` 工具类:
```html
```
小程序开发者工具会把 `my-class` 中的样式拆开成 `bg- #fafa00 text- 40px`,最终导致样式全部失效。
## 根本原因
插件默认只会转译 `class` 和 `hover-class`。外部样式类属于自定义属性,如果没有配置 [`customAttributes`](/docs/api/options/important#customattributes),就不会被识别处理。
## 解决方案
在插件选项里增加自定义属性的映射即可:
```js
customAttributes: {
'*': ['my-class'],
}
```
- `*` 代表匹配所有标签,你也可以改成具体的标签名或正则表达式。
- 支持传入 `Object` 或 `Map`,用于灵活地映射标签与属性的关系。
:::tip 多个外部样式类
如果组件同时暴露 `['my-class', 'title-class']`,直接把它们都写进同一个数组即可。
:::
## 扩展阅读
- 微信官方文档:[外部样式类](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#外部样式类)
- 插件配置项说明:[customAttributes](/docs/api/options/important#customattributes)
> 使用正则进行自定义匹配标签时,需要传入一个 `Map`,其中正则作为 `key`,数组作为 `value`。
---
## Tailwindcss 格式化
## prettier 插件
> 这是官方提供的包,
使用并在 `prettier` 注册 [`prettier-plugin-tailwindcss`](https://www.npmjs.com/package/prettier-plugin-tailwindcss)
## eslint 插件
使用并在 `eslint` 注册 [`eslint-plugin-tailwindcss`](https://www.npmjs.com/package/eslint-plugin-tailwindcss)
---
## group 和 peer 使用限制
## group 使用注意事项
在 `tailwindcss` 中,我们常常会这样写:
```html
group tapped
```
这样在最外层的 `div` 进入 `hover` 状态时,内部的子元素中的 `group-hover` 就会生效,从而改变样式。
然而,在小程序中,伪类 `:hover` 是不起作用的,取而代之的是 `hover-class` 这样一个属性,所以这种情况我们可以这么写:
```html
group tapped
```
这样在 `group` 进入 `hover` 状态时,`bg-yellow-400` 就会生效了。
相关 issue:[#14](https://github.com/sonofmagic/uni-app-vite-vue3-tailwind-vscode-template/issues/14)
## peer 使用注意事项
我们一般使用 `peer` 来标记一个元素,再使用各种 `peer-*` 来让它后续兄弟节点的样式生效。这些主要生成大量包含 `~` [后续兄弟选择器](https://developer.mozilla.org/zh-CN/docs/Web/CSS/Subsequent-sibling_combinator) 的 `css` 代码。
然而很不幸,在小程序中 `~` 这个选择器非常容易报错,它前面只能跟 `class` 选择器,不能跟伪类,不然会报错:
```scss
// 报错
// .xxx:invalid~.xxx-invalid:visible {
// visibility: visible;
// }
// 不报错
.xxx~.xxx-invalid:visible {
visibility: visible;
}
```
所以你要么就不使用 `peer` 特性,如果需要此特性请使用内嵌 `class` 的方式来使用:
```html
```
> 前一个方块按压后进入 `hover` 状态 ,后面那个就变成红色。
## 出现 unexpected token "~" 错误
出现这个错误后,你应该把对应报错的相关 `peer`、`peer-*` 删掉,注意是删掉,请不要注释,因为 `tailwindcss` 中也会从注释中提取字符串,所以注释掉是没有效果的。
删掉之后,你需要重新启动一下你的应用(例如 `yarn dev:weapp`),不然导致错误的 `css` 还是会存在,导致项目崩溃。
---
## 常见问题
:::info 组件外部样式类必读
自定义组件使用 `externalClasses` 时样式被拆分?请先查看《[组件外部样式类(externalClasses)的支持](/docs/issues/externalClasses)》,按照文档里的 `customAttributes` 配置即可解决。
:::
## 为什么我更改了 class 保存重新打包的时候热更新失效?
[[#93](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/93)]
目前微信开发者工具会默认开启代码自动热重载 `compileHotReLoad` 功能,这个功能在原生开发中表现良好,但在 `uni-app` 和 `taro` 等的框架中,存在一定的问题,参见 [issues#37](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/37),所以如果你遇到了此类问题,建议关闭 `compileHotReLoad` 功能。
## `disabled:opacity-50` 这类的 `tailwindcss` 工具类不生效?
这是由于微信小程序 `wxss` 选择器的原生限制,无法突破。参见 [issue#33](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/33)。
## `background-image` 为什么不能使用本地路径?
微信小程序在 `wxss` 中禁止 `background-image` 引用本地文件,解析时会直接报 `do-not-use-local-path` 错误。因此像 bg-[url('/images/homebg.png')] 这样的写法无法生效。请改用以下任一方式:
- 使用线上可访问的远程图片地址,例如 `bg-[url('https://example.com/bg.png')]`
- 将资源转成 `base64` 后内联到 `background-image`
- 改用 `` 组件渲染背景效果
选择合适方案后再通过 `tailwindcss` 编写样式,即可避免编译报错。
## 和原生组件一起使用注意事项
假如出现原生组件引入报错的情况,可以参阅 [issue#35](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/35),忽略指定目录下的文件,跳过插件处理,例如 `uni-app` 中的 `wxcomponents`。
如何更改?在传入的配置项 `cssMatcher`,`htmlMatcher` 这类配置,来过滤指定目录或文件。
## uni-app + Tailwind CSS v3 扫描 `src/uni_modules` 后生成异常 CSS
### 问题现象
当 `tailwind.config` 使用下面这种过宽的 `content` 配置:
```ts
content: ['./src/**/*.{html,js,ts,jsx,tsx,vue}']
```
并且项目里存在 `src/uni_modules/**/*` 第三方包时,Tailwind 可能扫描到依赖源码中的正则片段或示例文本,例如 `[a-zA-Z:_]`,并把它当成 arbitrary property class 提取。
在小程序场景下,再经过 `weapp-tailwindcss` 转译后,最终可能出现类似:
```css
._ba-zA-Z_c__B {
a-z-a--z:;
}
```
这样的异常产物。
### 根因
这类问题的根因不是业务代码真的写了这个 class,而是 Tailwind v3 的内容提取器误扫了第三方目录中的源码、文档或构建产物。
### 推荐配置
请显式排除 `src/uni_modules`:
```ts title="tailwind.config.ts"
export default {
content: [
'./index.html',
'./src/**/*.{html,js,ts,jsx,tsx,vue}',
'!./src/uni_modules/**/*',
],
}
```
### 最佳实践
- `content` 应尽量只覆盖业务源码目录
- 默认应排除 `uni_modules`、`node_modules`、`dist`、`unpackage`、文档和生成产物
- 如果必须扫描某个 `uni_modules` 包,应只精确包含其中真正承载模板类名的文件,而不是整个目录全量扫描
## 编译到 h5 / app 注意事项
有些用户通过 `uni-app` 等跨端框架,不止开发成各种小程序,也开发为 `H5`,然而 `tailwindcss` 本身就兼容 `H5` 了。此时你需要更改配置,我们以 `uni-app` 为例:
```js
const isH5 = process.env.UNI_PLATFORM === "h5";
// vue3 版本构建到 app, UNI_PLATFORM 的值为 app
// vue2 版本为 app-plus
const isApp = process.env.UNI_PLATFORM === "app-plus";
const WeappTailwindcssDisabled = isH5 || isApp;
// 然后在 h5 和 app 环境下把 webpack plugin 和 postcss for weapp 给禁用掉
// 我们以 uni-app-vue3-vite 这个 demo为例
// vite.config.ts
// vite 插件配置
const vitePlugins = [uni(),uvtw({
disabled: WeappTailwindcssDisabled
})];
export default defineConfig({
plugins: vitePlugins
});
// 同理 postcss 配置
// 假如不起作用,请使用内联postcss
const plugins = [require('autoprefixer')(), require('tailwindcss')()];
if (!WeappTailwindcssDisabled) {
plugins.push(
require('postcss-rem-to-responsive-pixel')({
rootValue: 32,
propList: ['*'],
transformUnit: 'rpx'
})
);
}
module.exports = {
plugins
};
```
## 报错 TypeError: Cannot use 'in' operator to search for 'CallExpression' in undefined
遇到这个问题是由于 `babel` 相关的包之间的版本产生了冲突导致的,这种时候可以删除掉 `lock` 文件(`yarn.lock`、`pnpm-lock.yaml`、`package-lock.json`),然后重新安装即可。
## taro webpack5 环境下,这个插件和外置额外安装的 `terser-webpack-plugin` 一起使用,会导致插件转义功能失效
相关 issue:[#142](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/142)
例如:`.h-4/6`、`!w-full` 正常会转义为`.h-4s6`、`.iw-full`,本插件失效后小程序开发者工具报编译错误 `.h-4\/6`、`.\!w-full`。
请压缩代码并不要使用[链接](https://docs.taro.zone/docs/config-detail/#terserenable)中的方法,太老旧了。
使用 `taro` 配置项里的的 `terser` 配置项,参见 [`terser` 配置项](https://docs.taro.zone/docs/config-detail#terser)。
> `terser` 配置只在生产模式下生效。如果你正在使用 `watch` 模式,又希望启用 `terser`,那么则需要设置 `process.env.NODE_ENV` 为 `production`。
也就是说,直接在开发 `watch` 模式的时候,设置环境变量 `NODE_ENV` 为 `production` 就行。
另外也可以不利用 `webpack` 插件压缩代码,去使用微信开发者工具内部的压缩代码选项。
## 为什么 space-y-1 这类写法不起作用?
相关 issue:[#108](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/108)
考虑到小程序的组件 `shadow root` 实现方式,默认情况下 `space` 这一类带有子选择器的,只对 `view` 元素生效。
即选择器变成了 `.space-y-1 > view + view`
这时候解决方案有 3 种:
- 组件外层套一层 `` 元素。
- `virtualHost` 解决方案,在自定义组件中添加 `options: { virtualHost: true }` 即可解决此问题。
- [`cssChildCombinatorReplaceValue`](/docs/api/options/general#csschildcombinatorreplacevalue) 配置项
## 使用 uni-app vite vue 注册插件时,发行到 h5 环境出现: [plugin:vite-plugin-uni-app-weapp-tailwindcss-adaptor] 'import' and 'export' may appear only with 'sourceType: "module"' (1:0) 错误
解决方案:
```js
// 注意:打包成 h5 和 app 都不需要开启插件配置
const isH5 = process.env.UNI_PLATFORM === "h5";
// vue3 版本构建到 app, UNI_PLATFORM 的值为 app
// vue2 版本为 app-plus
const isApp = process.env.UNI_PLATFORM === "app-plus";
const WeappTailwindcssDisabled = isH5 || isApp;
const vitePlugins = [uni(), uvwt({
disabled: WeappTailwindcssDisabled
})];
```
即 `h5` 环境和 `app` 环境都不开启我这个插件,因为本来这 2 个环境就是 `tailwindcss` 支持的环境,没必要开启插件转义。
## 使用 pnpm@8 插件注册失败问题
pnpm 8 这个版本改变了一些默认值,其中 `resolution-mode` 默认值变成了 `lowest-direct`。
这会导致所有的依赖,会被安装成你在 `package.json` 里注册的最低版本,这可能会造成一些问题。如何解决?
目录下创建一个 `.npmrc`,设置 `resolution-mode` 为 `highest`,然后重新安装,
或者,使用 `pnpm up -Li` 升级一下你 `package.json` 里的依赖包版本到最新即可。
## uni-app 在从v1升级到v2的过程中,如果使用了云函数相关功能,编译到小程序会出现问题
解决方案参见:
相关 issue:[#74](https://github.com/sonofmagic/weapp-tailwindcss/issues/74#issuecomment-1573033475)
## uni-app vue2 中的 css 使用 @import 引入其他 css,导致在 `rpx` 在H5下不生效
需要添加并配置 `postcss-import`,参见 [issues/75](https://github.com/sonofmagic/weapp-tailwindcss/issues/75#issuecomment-1574592907)。
你可以参考仓库中的 `demo/uni-app-vue3-vite` 来进行配置。
## 为什么使用 taro 写 jsx,js 时候,转义不生效?
这是因为 [patch](/docs/quick-start/this-plugin) 方法没有生效,这个指令是用来在运行时暴露 `tailwindcss` 上下文的,只有暴露成功,我们写的 `js` 里的样式,才会变精准转义,否则就会出现在 `jsx` 里写 `className` 不生效的情况。
## monorepo 项目中 arbitrary values 写法无效?
这可能是由于 tailwindcss 包被提升,导致项目获取不到正确的 tailwind 上下文,有两种解决方案。
- 配置 [tailwindcssBasedir](https://tw.icebreaker.top/docs/api/interfaces/UserDefinedOptions#tailwindcssbasedir)
- 禁止 `tailwindcss` 包被提升,具体配置方法可以去查阅各包管理器的说明文档
---
## 写在 js 中的 tailwindcss 任意值失效
`weapp-tailwindcss` 是允许你在 `js` 中编写任意值的,而且 `weapp-tailwindcss` 会自动帮你做好任意值的转译。
比如:
```js title="src/pages/index/index.js"
const xs = {
wrapper: 'px-[4px] h-[40px]',
}
```
那么在最终的产物中,编译结果会自动变为
```js title="dist/pages/index/index.js"
const xs = {
wrapper: 'px-_4px_ h-_40px_',
}
```
但是你这个文件,必须被 `tailwindcss` 感知到,并从里面提取到这 `2` 个 `class`。`weapp-tailwindcss` 才能通过和 `tailwindcss` 的通信,来完成这 `2` 个 `class` 的转译。
所以你这个源文件必须在 `tailwindcss@3` 中的 `tailwind.config.js` 中被 `content` 配置包括。或者 `tailwindcss@4` 被 `@source` 包括到,那这个自动转译的流程才能走完。
否则就会出现 `js` 转译没有进行, 导致开发者工具中审查元素时,出现:
```html
```
这种类名被切断的情况。
## 解决方案
### tailwindcss@3
检查你的 `tailwind.config.js` 中的 `content`,确认你出现类名被切断的源文件,被 `content` 包括。
文档地址: https://v3.tailwindcss.com/docs/configuration#content
### tailwindcss@4
检查你的 `@source`,确认你出现类名被切断的源文件,被 `@source` 包括。
文档地址: https://tailwindcss.com/docs/detecting-classes-in-source-files#explicitly-registering-sources
---
## 在 monorepo 中使用
在 `monorepo` 由于存在 `hoist` 机制,可能会导致 `weapp-tailwindcss` 和 `tailwindcss` 通信受阻,这时候需要显式的去指定 `tailwindcss` 的路径
这里我们以 `taro@4` 的配置 `config/index.ts` 配置为例
## Tailwindcss@3
```ts
const config = {
webpackChain(chain) {
chain.merge({
plugin: {
install: {
plugin: UnifiedWebpackPluginV5,
args: [
{
rem2rpx: true,
// highlight-next-line
tailwindcssBasedir: path.resolve(__dirname, '../'),
},
],
},
},
})
},
}
```
## Tailwindcss@4
```ts
const config = {
webpackChain(chain) {
chain.merge({
plugin: {
install: {
plugin: UnifiedWebpackPluginV5,
args: [
{
rem2rpx: true,
// highlight-next-line
cssEntries: [
// app.css 的路径
path.resolve(__dirname, '../src/app.css'),
],
},
],
},
},
})
},
}
```
使用这样的配置,就能在 `monorepo` 中使用了
---
## 生成样式只作用于view和text标签
在微信小程序中,`darkMode` 设置为 `class`/ `selector` 后,`dark:className` 类选择器在 `button` 上无效,看生成样式只作用于 `view` 和 `text` 标签
这是由于小程序是不接受 `*` 这样一个选择器的。
默认情况下, `weapp-tailwindcss` 会把 `*` 选择器转化成 `view,text` 的选择器
这个配置可以通过 `cssSelectorReplacement.universal` 进行更改,从而适配更多标签。
详见 [cssSelectorReplacement.universal 文档](/docs/api/options/important#cssselectorreplacement)
---
## 原生头条小程序使用 TailWindCSS
> 以下内容由使用 `weapp-tailwindcss` 的热心网友提供,十分感谢!
## 创建项目
创建项目 `test-miniapp`, 进入项目目录并初始化 `package.json`
```sh
cd test-miniapp
npm init -y
```
新建小程序开发目录 `src`,对应的小程序代码,生成目标代码目录为 `dist`
此时目录结构如下所示:
```
test-miniapp
-- src
-- dist
-- package.json
```
## 安装 gulp 及插件
- 本地安装 `gulp`
```sh
npm i -D gulp
```
- 安装 gulp 模块及插件
```sh
npm i -D gulp gulp-postcss gulp-plumber del@^6
```
## 安装与配置 tailwindcss
- 安装 tailwindcss
```sh
npm i -D tailwindcss@3 postcss autoprefixer
```
- 初始化 tailwindcss 配置文件
```sh
npx tailwindcss init
```
- 创建 `postcss.config.js` 并注册 `tailwindcss`
```js
module.exports = {
plugins: {
tailwindcss: {},
// 假如框架已经内置了 `autoprefixer`,可以去除下一行
autoprefixer: {},
}
}
```
- 配置 `tailwind.config.js`
```js
/** @type {import('tailwindcss').Config} */
module.exports = {
// 不在 content 包括的文件内的 class,不会生成对应的 css 工具类
content: ['./src/**/*.{ttml,js}'],
theme: {
extend: {},
},
plugins: [],
}
```
- 代码引入 `tailwindcss`,打开 `src/app.ttss`
```css
@tailwind base;
@tailwind components;
@tailwind utilities;
```
## 配置 vscode 插件
### Prettier - Code formatter
安装插件
```sh
npm i -D prettier prettier-plugin-tailwindcss
```
配置 `prettier.config.js`
```js
module.exports = {
// 行尾加分号
semi: false,
// 使用单引号
singleQuote: true,
// 配置文件类型
overrides: [
{
files: '*.ttml',
options: { parser: 'html' },
},
{
files: '*.ttss',
options: { parser: 'css' },
},
],
plugins: ['prettier-plugin-tailwindcss'],
}
```
将小程序的文件包括进来,设置:`首选项->工作区->设置->扩展->Prettier->Prettier: Document Selectors`
```txt
**/*.ttml
**/*.ttss
```
- 字节小程序开发助手(微信小程序是这个:WXML - Language Service)
### Tailwind CSS IntelliSense
并配置:`首选项->工作区->设置->扩展->Tailwind CSS IntelliSense->Tailwind CSS: Include Languages`
```
项:ttml,值:html
```
### Gulp Tasks
- Gulp Tasks
安装插件
```sh
npm i -D weapp-tailwindcss-webpack-plugin
```
配置 `gulpfile.js`,需要注意的事,在面板执行 `serve` 后,即使后来停止了任务,程序里的监听 `watch` 也不会停,使得后续再启动 `serve` 后,会有多个监听 `watch` 和多个监听处理程序 `watchHandler`,重复处理文件。所以停止后再启动 `serve`,应该关闭 `vscode` 后重新打开
```js
const { src, dest, series, parallel, task, watch } = require('gulp')
const postcss = require('gulp-postcss')
const plumber = require('gulp-plumber')
const path = require('path')
const del = require('del')
const tailwindcssGulp = require('weapp-tailwindcss-webpack-plugin/gulp')
// 在 gulp 里使用, 先使用 postcss 转化 css, 触发 tailwindcss,然后转化 transformWxss,最后转化 transformJs, transformWxml
const {
transformJs,
transformWxml: transformHtml,
transformWxss: transformCss,
} = tailwindcssGulp.createPlugins({
rem2rpx: true,
})
const config = {
srcDir: 'src',
distDir: 'dist',
cssExt: '.ttss',
jsExt: '.js',
htmlExt: '.ttml',
}
function transformCssFiles() {
return src(`${config.srcDir}/**/*${config.cssExt}`)
.pipe(plumber())
.pipe(postcss())
.pipe(transformCss())
.pipe(dest(`${config.distDir}`))
}
function transformJsFiles() {
return src(`${config.srcDir}/**/*${config.jsExt}`)
.pipe(plumber())
.pipe(transformJs())
.pipe(dest(`${config.distDir}`))
}
function transformHtmlFiles() {
return src(`${config.srcDir}/**/*${config.htmlExt}`)
.pipe(plumber())
.pipe(transformHtml())
.pipe(dest(`${config.distDir}`))
}
function copyOtherFiles() {
return src([
`${config.srcDir}/**/*`,
`!${config.srcDir}/**/*${config.cssExt}`,
`!${config.srcDir}/**/*${config.jsExt}`,
`!${config.srcDir}/**/*${config.htmlExt}`,
]).pipe(dest(`${config.distDir}`))
}
function promisify(task) {
return new Promise((resolve, reject) => {
if (task.destroyed) {
resolve(undefined)
return
}
task.on('finish', resolve).on('error', reject)
})
}
// type 取值: changed, added, deleted
async function watchHandler(type, file) {
if (type == 'deleted') {
await del([
file.replace(
`${config.srcDir}${path.sep}`,
`${config.distDir}${path.sep}`
),
])
} else {
const extName = path.extname(file)
switch (extName) {
case config.cssExt:
await promisify(transformCssFiles())
break
case config.jsExt:
await promisify(transformCssFiles())
await promisify(transformJsFiles())
break
case config.htmlExt:
await promisify(transformCssFiles())
await promisify(transformHtmlFiles())
break
default:
await promisify(copyOtherFiles())
}
}
}
function watchTask() {
const watcher = watch([`${config.srcDir}/**/*`])
watcher
.on('change', function (file) {
console.log(`${file} is changed`)
watchHandler('changed', file)
})
.on('add', function (file) {
console.log(`${file} is added`)
watchHandler('added', file)
})
.on('unlink', function (file) {
console.log(`${file} is deleted`)
watchHandler('deleted', file)
})
}
function clean() {
return del(config.distDir, { force: true })
}
const buildTasks = [
transformCssFiles,
transformJsFiles,
transformHtmlFiles,
copyOtherFiles,
]
// 注册服务任务
task('serve', series(...buildTasks, watchTask))
// 注册清除任务
task('clean', parallel(clean))
```
---
## rpx 任意值颜色或长度单位二义性与解决方案
## 这是一个什么问题?
在不使用 `weapp-tailwindcss` 的情况下,你直接写这样的 `rpx` 写法:
```html
```
最终它会生成这样的 `css`:
```css
.text-\[32rpx\] {
color: 32rpx;
}
```
为什么 `rpx` 这个好端端的长度单位,会变成颜色呢?
原因在于 `rpx` 不是一个标准的 `W3C` 规定的 `CSS` 长度单位,这是微信小程序自己定的 `WXSS` 单位。
## 什么是 **二义性**?
`tailwindcss` 中有些原子类具有 **二义性**,比如:
- `text-[]`
- `border-[]`
- `bg-[]`
- `outline-[]`
- `ring-[]`
其中 `text-[]` 中的 `text-[16.16px]` 生成的 css 是 `font-size: 16.16px;`, 而 `text-[#123456]` 生成的 css 是 `color: #123456;`;
这就是原子类的 **二义性**
---
而 `tailwindcss` 在针对具有**二义性**的任意值写法:
这些会去**校验括号**内的任意值,是否为有效的 `CSS` 长度单位!
如果为 `true`,则生成出长度单位的 `css` 节点,反之则生成出颜色单位的 `css` 节点:
```css
/* text-[16px] */
.text-\[16px\] {
font-size: 16px
}
/* text-[#fafafa] */
.text-\[\#fafafa\] {
--tw-text-opacity: 1;
color: rgb(250 250 250 / var(--tw-text-opacity))
}
```
那么问题来了,`rpx` 在单位校验的时候,由于不认识这个单位,导致单位无效所有被分到了颜色组。
```css
/* text-[32rpx] */
.text-\[32rpx\] {
--tw-text-opacity: 1;
color: 32rpx;
}
```
所以造成了这个问题!那么如何解决呢?
## 目前插件的解决方案
目前,我做了一个解决方案,我在 `weapp-tailwindcss` 植入了一个逻辑,使得插件可以通过分析 `tailwindcss` 运行时代码,来打上支持 `rpx` 单位的补丁,使得 `tailwindcss` 支持这样的写法,生成出长度单位的 `css`。
这也是为什么要让大家去执行 `weapp-tw patch` 的原因。
这个解决方案,最新的 `3.x` 和 `4.x` 版本,都是有效的。
## 强制CSS单位的解决方案
我们可以在使用这些带有**二义性**的单位的时候,可以通过 `length` 或 `color` 这种的前缀来指定它应该是什么,例如:
```html
...
...
...
...
```
这样就通过指定的方式,直接跳过了长度单位校验,生成出长度单位的 `css` 了!
```css
.text-\[length\:22rpx\] {
font-size: 22rpx
}
```
同样你可以使用这 2 个前缀来指定 `css` 变量的生成形式:
```html
...
...
```
## 参见
- `tailwindcss` 中的[添加自定义样式](https://tailwindcss.com/docs/adding-custom-styles#resolving-ambiguities)
- 相关 Issue:[#110](https://github.com/sonofmagic/weapp-tailwindcss/issues/110)、[#110](https://github.com/sonofmagic/weapp-tailwindcss/issues/109)
---
## `Tarojs` 中使用 `terser` 压缩代码
在 `taro` `webpack5` 环境下,这个插件和外置额外安装的 `terser-webpack-plugin` 一起使用,会导致插件转义功能失效
相关 issue:[#142](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/142)
## 现象
例如:`.h-4/6`、`!w-full` 正常会转义为`.h-4s6`、`.iw-full`,本插件失效后小程序开发者工具报编译错误 `.h-4\/6`、`.\!w-full`。
## 解决方案
请压缩代码并不要使用[链接](https://docs.taro.zone/docs/config-detail/#terserenable)中的方法,太老旧了。
使用 `taro` 配置项里的的 `terser` 配置项,参见 [`terser` 配置项](https://docs.taro.zone/docs/config-detail#terser)。
> `terser` 配置只在生产模式下生效。如果你正在使用 `watch` 模式,又希望启用 `terser`,那么则需要设置 `process.env.NODE_ENV` 为 `production`。
也就是说,直接在开发 `watch` 模式的时候,设置环境变量 `NODE_ENV` 为 `production` 就行。
另外也可以不利用 `webpack` 插件压缩代码,去使用微信开发者工具内部的压缩代码选项。
## 配置参考
```ts title="config/index.ts"
{
terser: {
enable: true,
config: {
// 相关配置项
},
},
}
```
然后你想要在开发时,就生效,那就需要传入 `NODE_ENV=production` 环境变量,例如:
```json title="package.json"
{
"scripts":{
"dev:weapp": "cross-env NODE_ENV=production npm run build:weapp -- --watch",
}
}
```
`cross-env` 没有安装的可以安装一下
---
## H5 端原生 toast 样式偏移问题
在使用 `tailwindcss` 的时候,编译到 `h5` 平台,使用 `uni.toast` / `taro.toast` 时,出现下列的效果

`tailwindcss` 的 `base` 中的 `preflight` 影响这个 `uni.toast` 的样式
这是由于 `preflight.css` 中默认会添加下方的样式
```css
img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
display: block; /* 1 */
vertical-align: middle; /* 2 */
}
```
这导致了 `svg` 变成了 `display: block;` 的状态
解决方案也非常的简单, 在 `app.wxss` 使用样式进行覆盖:
```scss
.uni-toast{
svg {
display: initial; // 重新初始化 uni-toast 里的样式进行覆盖 覆盖
}
}
```
假如你使用的是 `uni-app`,那么还可以使用样式条件编译的方式来做:
```scss
/* #ifdef H5 */
svg {
display: initial;
}
/* #endif */
```
---
## 和 NutUI 一起使用
`taro` 使用 [NutUI](https://nutui.jd.com) 的 `vue` 和 `react` 版本的共同注意点:
由于 [NutUI](https://nutui.jd.com) 必须要配合 `@tarojs/plugin-html` 一起使用。
然而 `@tarojs/plugin-html` 这个插件,默认情况下它会移除整个 `tailwindcss` 注入的 `css var` 区域块,这会造成所有 `tw-*` 相关变量找不到,导致样式大量挂掉的问题。例如(`drop-shadow-2xl`,`translate-1/2` 等样式)。
此时可以启用这个插件的 [`injectAdditionalCssVarScope`](/docs/api/options/important#injectadditionalcssvarscope) 配置项,把它设为 `true`,这能在插件内部启用功能,来重新注入整个 `tailwindcss` 的 `css` 中的 `var` 区域块( `tailwindcss@3` )。
按照初始的配置,只需要添加一行即可,示例如下:
```diff
const { UnifiedWebpackPluginV5 } = require('weapp-tailwindcss/webpack')
{
mini: {
webpackChain(chain, webpack) {
chain.merge({
plugin: {
install: {
plugin: UnifiedWebpackPluginV5,
args: [{
rem2rpx: true,
+ injectAdditionalCssVarScope: true
}]
}
}
})
}
}
}
```
## 可能有用但是过时的方案(部分 taro 版本有用)
~~需要去配置一下 `postcss-html-transform` 这个插件~~(实在找不到方法可以尝试一下)
```js
// config/index.js
config = {
// ...
mini: {
// ...
postcss: {
htmltransform: {
enable: true,
// 设置成 false 表示 不去除 * 相关的选择器区块
// 假如开启这个配置,它会把 tailwindcss 整个 css 的 var 区域块直接去除掉
// 需要用 config 套一层,官方文档上是错的
config: {
removeCursorStyle: false,
}
},
},
},
}
```
## 参见
- [taro 官方文档](https://docs.taro.zone/docs/use-h5#插件-postcss-配置项)
- 相关 Issue:[#155](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/155)
---
## 和 Taroify 一起使用
`taro` 使用 [Taroify](https://taroify.github.io/taroify.com/) 的共同注意点:
由于 [Taroify](https://taroify.github.io/taroify.com/) 引入后,会导致 `tailwindcss` 的样式被覆盖,[Taroify](https://taroify.github.io/taroify.com/) 样式的优先级会高于 `tailwindcss`。
## 解决方案
### 修改Taroify引入方式
按照[Taroify](https://taroify.github.io/taroify.com/) 修改引入方式,将 `taroify` 引入方式改成按需引入
```bash npm2yarn
# 安装插件
npm i babel-plugin-import
```
修改Babel配置文件,修改组件和图标样式的引入方式为手动引入
```js
// babel.config.js
module.exports = {
plugins: [
[
'import',
{
libraryName: '@taroify/core',
libraryDirectory: '',
// 这修改为false
style: false,
// style: false,
},
'@taroify/core',
],
[
'import',
{
libraryName: '@taroify/icons',
libraryDirectory: '',
camel2DashComponentName: false,
// 这里修改为false
style: false,
// style: () => "@taroify/icons/style",
customName: name => name === 'Icon' ? '@taroify/icons/van/VanIcon' : `@taroify/icons/${name}`,
},
'@taroify/icons',
],
],
}
```
### 修改引入样式顺序
修改根目录下的样式引入顺序,优先引入[Taroify](https://taroify.github.io/taroify.com/) 的样式,再引入Tailwindcss的样式
```tsx
// src/app.tsx
// ...
```
```scss
// src/app.scss
@use 'tailwindcss/base';
@use 'tailwindcss/components';
@use 'tailwindcss/utilities';
```
## 参见
- [Taroify 官方文档](https://taroify.github.io/taroify.com/)
---
## 和 wot-design-uni 一起使用
---
## v1 版本插件常见问题,使用最新版本插件无须参考
## 我在 `js` 里写了 `tailwindcss` 的任意值,为什么没有生效?
详见 [issue#28](https://github.com/sonofmagic/weapp-tailwindcss-webpack-plugin/issues/28)
A: 因为这个插件,主要是针对, `wxss`,`wxml` 和 `jsx` 进行转义的,`js` 里编写的 `string` 是不转义的。如果你有这样的需求可以这么写:
```js
const cardsColor = reactive([
replaceJs('bg-[#4268EA] shadow-indigo-100'),
replaceJs('bg-[#123456] shadow-blue-100')
])
```
> 你不用担心把代码都打进来导致体积过大,我在 'weapp-tailwindcss-webpack-plugin/replace' 中,只暴露了2个方法,代码体积 1k左右,esm格式。
## replaceJs 跨端注意点
就是在常见问题中的 `replaceJs` 这个方法原先是为小程序平台设计的,假如你一份代码,需要同时编译到小程序和 `h5` 平台,可以参考如下的封装:
```js
// util.js
// uni-app 的条件编译写法
export function replaceClass(str) {
// #ifdef H5
return str
// #endif
return replaceJs(str)
}
// or 环境变量判断
export function replaceClass(str) {
// 需要根据自己目标平台自定义,这里仅仅给一些思路
if(process.env.UNI_PLATFORM === 'h5'){
return str
}
return replaceJs(str)
}
// then other.js
const cardsColor = reactive([
replaceClass('bg-[#4268EA] shadow-indigo-100'),
replaceClass('bg-[#123456] shadow-blue-100')
])
```
这样就能在多端都生效了。
---
## 从 v1 迁移到 v2
在 `2.x` 版本中,可以把之前使用的 `webpack` 插件,全部更换为 `UnifiedWebpackPluginV5` 插件,不过 `vite` 插件的导出有一些小变化:
`1.x`:
```js
```
`2.x`:
```js
// UnifiedViteWeappTailwindcssPlugin 就是新的插件
```
另外新的 `UnifiedWebpackPluginV5` 可以直接从 `weapp-tailwindcss-webpack-plugin` 引入,同时在新的 `UnifiedWebpackPluginV5` 中,之前所有的配置项都被继承了过来,只需要用它直接替换原先插件即可。
另外不要忘记把:
```json
"scripts": {
+ "postinstall": "weapp-tw patch"
}
```
添加进你的 `package.json` 里,然后清除原先的打包缓存之后重新打包运行。
---
## 从 v2 迁移到 v3
v3 版本相比于 v2, 主要是删去一些过时的功能,配置项,同时会改变插件的默认值,使得整体插件变得更易用,更容易安装
假如你没有用到什么复杂自定义配置,那么完全可以平滑升级上来。
## 配置项改动
### 删除的配置项
- 删去 `replaceUniversalSelectorWith` 选项,使用 `cssSelectorReplacement.universal` 来代替,后者参数覆盖前者
- 删去 `minifiedJs` 选项,现在完全遵从用户的配置,用户压缩就压缩,反之亦然
- 删去 `jsEscapeStrategy` 选项,现在默认只有一种模式 `replace`/ 不再提供 `regenerate` 模式
- 删去 `customReplaceDictionary` 的 `complex` 模式,只内置 `simple` 模式 (你如果还要 `complex` 模式 ,可以从 `@weapp-core/escape` 引入,再传入 `customReplaceDictionary` 配置项即可)
- `cssMatcher`/`htmlMatcher`/`jsMatcher`/ `mainCssChunkMatcher` / `wxsMatcher` 不再能够传入 `glob` 表达式(例如`**/*.html`),现在都是传入一个方法: `(name: string) => boolean`。要兼容原先的 `glob` 表达式,你可以通过 `minimatch` 把 `glob` 表达式转化成正则来兼容原先的配置
- `cssPreflightRange` 只存在一种模式,为 `all`, 之前的 `view` 选项交给 `cssSelectorReplacement.universal` 进行托管
### 增加的配置项
- `rem2rpx` : 类型 `rem2rpx?: boolean | rem2rpxOptions`
rem 转 rpx 配置,默认 **不开启**,可传入配置项,配置项见
这个配置项代表插件内置了 `postcss-rem-to-responsive-pixel` ,不过默认不开启,传入一个 `true` 相当于传入配置:
```js
{
// 32 意味着 1rem = 32rpx
rootValue: 32,
// 默认所有属性都转化
propList: ['*'],
// 转化的单位,可以变成 px / rpx
transformUnit: 'rpx',
}
```
当然你也可以传入 `rem2rpxOptions` 这样一个 `object` 进行自定义
#### 为什么默认不开启?
1. 为了从 `2.x` 版本可以平滑的过渡到 `3.x`
2. 从我的视角看,内置 `postcss` 插件功能,虽然整体集成度上更高了,但是对其他开发者可能不是那么自由,比如在 `2.x` 时候,由于 `postcss-rem-to-responsive-pixel` 是外置的,所以开发者可以自由的决定它的加载顺序和加载逻辑,但是内置之后都是我决定的。不过内置好处也有,就是开箱即用
### 增强的配置项
- `cssChildCombinatorReplaceValue`, `cssSelectorReplacement.root`,`cssSelectorReplacement.universal` 现在都可以接受字符串数组了,它们可以自动展开,防止选择器格式化错误问题
### 修改的默认值
- `cssPreflightRange` 从 `'view'` 变为 `undefined`, 现在 `all` 的作用变成了在 `tailwindcss` 变量注入区域的选择器,添加一个 `:not(not)` 的选择器作为全局选择器的替代
- `cssSelectorReplacement.universal` 从 `'view'` 变为 `['view', 'text']`, 这意味着 `*` 选择器会被展开成 `view,text` 以及对应方式
- `cssChildCombinatorReplaceValue` 从 `'view + view'` 变为 `['view']`
- `replaceUniversalSelectorWith`,`jsEscapeStrategy`,`minifiedJs` 选项被删除,所以不再保留默认值
### 现在选项合并,数组默认行为变为覆盖,原先是合并
```js
const options = getOptions(input,defaults)
defaults: ['a','b'], input:['c']
// before:
options == ['a','b','c']
// after:
options == ['c']
```
---
## 从 v3 迁移到 v4
`tailwindcss@4` 改动较大,直接变成了一个样式预处理器,和 `sass` / `less` 类似,所以你不应该让 `tailwindcss@4` 和 `sass`, `less` 一起使用。
所以关于这方面的改动会比较多, 可能你需要把很多 `.scss`,`.less` 文件后缀改成 `.css`
`v4` 版本相比于 `v3`, 影响功能的重大变动较少,假如你没有用到什么复杂自定义配置,那么完全可以平滑升级上来。
## 重大变更
1. 移除 `jsAstTool` 的 `ast-grep` 支持,现在全部使用 `babel` 进行 `ast` 处理,假如你使用了这个配置,你可以保持不动,或者你可以把它删掉。
## 特性更新
1. 添加 `@weapp-tailwindcss/merge` 包作为小程序版本的 `tailwind-merge`
1. 增加 `ignoreTaggedTemplateExpressionIdentifiers` 和 `ignoreCallExpressionIdentifiers` 配置,用于和 `@weapp-tailwindcss/merge` 结合起来使用
1. 在安装 `@weapp-tailwindcss/merge` 时自动设置 `ignoreCallExpressionIdentifiers` 为 `['twMerge', 'twJoin', 'cva']` 默认不进行转义里面的字面量
1. 更改 `cssChildCombinatorReplaceValue` 默认值从 `['view']` -> `['view', 'text']` 为了更好的小程序开发体验
## 重构
1. 移除 `@babel/generator` 依赖
2. 去除 `weapp-tailwindcss/postcss` 导出,代替可直接安装使用 `@weapp-tailwindcss/postcss`
3. 增加 `weapp-tailwindcss/escape` 来取代 `weapp-tailwindcss/replace`, `weapp-tailwindcss/replace` 导出被移除
4. 项目 `monorepo` 区分包
5. 项目打包方式从 `rollup` 变为 `tsup`
## pnpm@10.x
假如你已经升级到了 `pnpm@10.x`,安装依赖后需要执行 `pnpm approve-builds weapp-tailwindcss` 将其加入 `onlyBuiltDependencies`,以便 `postinstall` 等 `npm hook` 能正常运行
---
## 使用 arbitrary values
`arbitrary values` 是 `tailwindcss v3` 的重要更新内容,幸运的是你使用了本插件。
使得你可以使用 `tailwindcss v3` 强大的 `arbitrary values` 功能。
比如:
```html
bg-[#fafa00]
bg-[#098765]
p-[20px] -mt-2 mb-[-20px] margin的jit 不能这么写 -m-[20px]
w-[300rpx] text-black text-opacity-[0.19]
min-w-[300rpx] max-h-[100px] text-[20px] leading-[0.9]
max-w-[300rpx] min-h-[100px] text-[#dddddd]
Hello
border-[10px] border-[#098765] border-solid border-opacity-[0.44]
1
2
3
```
or `@apply`
```html
world
```
详见 [tailwindcss/using-arbitrary-values 章节](https://tailwindcss.com/docs/adding-custom-styles#using-arbitrary-values)
---
## js 中的精确转化与忽略
默认对所有 `jsx`、`js`、`wxml`、`wxss` 中出现的 `tailwindcss` 运行时工具类进行转化,如果不需要转化可以使用 `weappTwIgnore` 标识符来进行忽略:
例如:
```js
classArray
// weappTwIgnore 就是 String.raw ,所以它的结果就是后面字符串的结果
const weappTwIgnore = String.raw
const classArray = [
'text-[30rpx]',
weappTwIgnore`bg-[#00ff00]`
]
```
此时只有 `'text-[30rpx]'` 会被转化,`'bg-[#00ff00]'` 会被忽略。
> 默认情况下仅会忽略与 `weappTwIgnore` 有直接关系的标记模板,例如从包里导入后重命名、或在同一文件里一路别名过去的写法。简单的 `String.raw` 别名会继续参加转译,防止误杀。
如果需要自定义别名,可以包装一层函数并在配置里显式加入该别名,例如:
```js
const alias = (...args) => String.raw(...args)
// 在 ignoreTaggedTemplateExpressionIdentifiers 中加入 'alias'
```
或者直接使用 `ignoreTaggedTemplateExpressionIdentifiers` 配置追加其它标识符。
---
## weapp-tailwindcss 导出总览
> 本文根据 `packages/weapp-tailwindcss/package.json` 的 `exports` 字段整理,帮助你在不同框架/构建场景中快速定位合适的入口文件。
weapp-tailwindcss 同时提供 ESM 与 CommonJS 入口,并内置多个二级导出以适配 webpack、Vite、Gulp、Tailwind 宏等不同组合。下面按用途分类进行说明。
## 核心插件入口
| 导出路径 | 说明 | 典型用法 |
| --- | --- | --- |
| `weapp-tailwindcss` | 聚合入口:`createPlugins`、`UnifiedWebpackPluginV5`、`UnifiedViteWeappTailwindcssPlugin` 等常用工厂齐备 | `import { UnifiedWebpackPluginV5 } from 'weapp-tailwindcss'`
| `weapp-tailwindcss/webpack` | webpack@5 适配入口(uni-app CLI、mpx、原生小程序等) | `const { UnifiedWebpackPluginV5 } = require('weapp-tailwindcss/webpack')`
| `weapp-tailwindcss/webpack4` | webpack@4 适配入口(旧版 Taro/uni-app 项目) | `import { UnifiedWebpackPluginV4 } from 'weapp-tailwindcss/webpack4'`
| `weapp-tailwindcss/vite` | Vite 插件入口(Taro Vite、weapp-vite 等) | `import { UnifiedViteWeappTailwindcssPlugin } from 'weapp-tailwindcss/vite'`
| `weapp-tailwindcss/core` | 暴露 `createContext` 等底层 API,可自定义 transform 流程 | `import { createContext } from 'weapp-tailwindcss/core'`
## 配置、工具与周边
| 导出路径 | 说明 | 场景 |
| --- | --- | --- |
| `weapp-tailwindcss/defaults` | 默认插件配置、补丁行为等常量 | 查看/复用默认选项
| `weapp-tailwindcss/presets` | 官方预设集合(差异化策略、Tailwind 配置等) | 扩展或组合默认行为
| [`weapp-tailwindcss/reset`](./reset) | 内置默认 `button` reset,可通过 `buttonReset` 选项禁用或改写选择器 | `@plugin 'weapp-tailwindcss/reset';`
| `weapp-tailwindcss/types` | TypeScript 类型定义便捷入口 | `import type { UserDefinedOptions } from 'weapp-tailwindcss/types'`
| `weapp-tailwindcss/escape` | `replaceWxml`、`isAllowedClassName` 等字符串处理工具 | 单独处理模板/字符串时复用
| `weapp-tailwindcss/postcss-html-transform` | 针对 HTML/WXML 的 PostCSS 转换器 | 自定义 PostCSS 流程
| `weapp-tailwindcss/css-macro` | Tailwind CSS 宏工具(JS/TS) | 在代码中动态生成原子类
| `weapp-tailwindcss/css-macro/postcss` | 宏工具的 PostCSS 版本 | 构建期宏替换
| `weapp-tailwindcss/gulp` | Gulp 插件入口 | 传统 Gulp 构建链集成
| `weapp-tailwindcss/package.json` | 包元数据 | 读取版本号等信息
> 补充:如果你需要的是“可直接导入的静态 reset 样式资源”,请使用独立包 [`@weapp-tailwindcss/reset`](/docs/community/reset),而不是这里的 `weapp-tailwindcss/reset` 插件入口。
## 样式资源
| 导出路径 | 说明 | 引用示例 |
| --- | --- | --- |
| `weapp-tailwindcss/index.css` (`weapp-tailwindcss/index`) | 默认 runtime 样式(==推荐直接引用==) | `@import 'weapp-tailwindcss/index.css';`
| `weapp-tailwindcss/preflight.css` (`weapp-tailwindcss/preflight`) | 小程序专用 Preflight | `@import 'weapp-tailwindcss/preflight.css';`
| `weapp-tailwindcss/theme.css` (`weapp-tailwindcss/theme`) | 主题变量定义 | `@import 'weapp-tailwindcss/theme.css';`
| `weapp-tailwindcss/utilities.css` (`weapp-tailwindcss/utilities`) | 原子类集合 | `@import 'weapp-tailwindcss/utilities.css';`
| `weapp-tailwindcss/with-layer.css` (`weapp-tailwindcss/with-layer`) | layer 版样式,适配 Tailwind v4 layer 写法 | `@import 'weapp-tailwindcss/with-layer.css';`
| `weapp-tailwindcss/uni-app-x.css` (`weapp-tailwindcss/uni-app-x`) | uni-app x 定制样式 | `@import 'weapp-tailwindcss/uni-app-x.css';`
| `weapp-tailwindcss/css` | 指向 `css/index.css`,兼容旧目录结构 | `@import 'weapp-tailwindcss/css';`
> ⚠️ 注意:部分构建工具(例如 `postcss-import`、mpx CLI)在解析裸包名 `weapp-tailwindcss` 时可能回退到 JS 入口(`dist/index.js`),并抛出 “Unknown word "use strict"”。请显式写成 `@import 'weapp-tailwindcss/index.css'`,或在本地创建中转 `app.css` 后再导入。
## 其他导出
- `weapp-tailwindcss/*`:保留通配符路径,兼容历史文件结构;建议优先使用上表列出的稳定入口。
- 所有 JS 模块同时提供 `import` 与 `require` 两种格式,TS 项目结合 `types` 入口即可获得完整声明。
想进一步了解各模块暴露的 API,可以查阅 [`weapp-tailwindcss` API 总览](../api/index.md) 或直接阅读对应类型定义与源码。
---
## 选项概览
该章节的详细配置已经迁移至 [API / 配置项文档](/docs/api/interfaces/UserDefinedOptions)。
- [允许的类名写法](/docs/options/arbitrary-values)
- [注释用法与忽略开关](/docs/options/comments)
如果你在升级过程中需要参考原先的配置写法,请参见上方链接。
---
## `weapp-tailwindcss/reset`
`weapp-tailwindcss/reset` 提供一组面向小程序生态的 reset 插件能力,默认会:
- 清除所有 `button` 的原生样式(padding / 颜色 / border 等),让它的表现和 `view` / `text` 一致;
- 将 `` / `` 统一为 `display: block`,并限制为 `max-width: 100%`、`height: auto`。
你可以通过选项控制是否注入这些规则、改写选择器 / 声明,甚至追加自定义 reset。
> ℹ️ `weapp-tailwindcss/reset` 目前是兼容导出层,实际实现来自 `@weapp-tailwindcss/reset`。老项目可以继续使用原入口,新项目也可以直接从 `@weapp-tailwindcss/reset` 导入。
> ℹ️ 当你传入 `.class` / `#id` 作为选择器时,插件会自动转换为 `[class~="class"]` / `[id="id"]`,确保它们仍属于 base layer,不会破坏其他层级。
## 可用选项
- `preset?: 'minimal' | 'form' | 'content' | 'media' | 'all' | ResetPreset[]`
- `buttonReset?: false | ResetConfig`
- `imageReset?: false | ResetConfig`
- `inputReset?: false | ResetConfig`
- `textareaReset?: false | ResetConfig`
- `listReset?: false | ResetConfig`
- `navigatorReset?: false | ResetConfig`
- `videoReset?: false | ResetConfig`
- `extraResets?: ResetConfig[]`
```ts
interface ResetConfig {
selectors?: string[] // 支持元素 / 类名 / ID
declarations?: Record
pseudo?: Record // 注入到 ::after
}
```
设置为 `false` 即可关闭对应默认 reset;当提供类名 / ID 时会自动转换为 `[class~="foo"]` / `[id="bar"]`。
对于 `inputReset`、`textareaReset`、`listReset`、`navigatorReset`、`videoReset` 这类默认未开启的内置项,如果你直接传入配置对象,插件也会自动启用对应 reset,不必先额外声明 `preset`。
```ts
reset({
inputReset: {
selectors: ['.wx-reset-input'],
},
videoReset: {
selectors: ['.wx-reset-video'],
},
})
```
## preset
`preset` 用来快速启用一组内置 reset。默认不传时等价于 `minimal`,保持和旧版本一致,只注入 `button` 与 `image`。
- `minimal`:`button` + `image`
- `form`:`minimal` + `input` + `textarea`
- `content`:`minimal` + `ul/ol` + `navigator/a`
- `media`:`minimal` + `video`
- `all`:启用全部内置 reset
你也可以组合多个 preset:
```ts
reset({
preset: ['content', 'media'],
})
```
## Tailwind CSS v3 用法
```ts title="tailwind.config.ts"
export default {
plugins: [
// 默认注入 button/image reset
reset(),
// 完全自定义
reset({
preset: 'form',
buttonReset: {
selectors: ['.wx-reset-btn', '#primary-btn'],
declarations: {
padding: '0',
backgroundColor: 'transparent',
},
pseudo: {
border: 'none',
},
},
imageReset: {
selectors: ['.wx-reset-image'],
declarations: {
display: 'inline-block',
borderWidth: '0',
},
},
listReset: {
selectors: ['.wx-reset-list'],
},
extraResets: [
{
selectors: ['.wx-reset-view'],
declarations: {
display: 'block',
borderWidth: '0',
},
pseudo: {
borderColor: 'transparent',
},
},
],
}),
],
}
```
关闭默认 reset:
```ts
reset({
buttonReset: false,
imageReset: false,
})
```
即使启用了 `preset`,你仍然可以通过把单项设置为 `false` 的方式精确关闭内置 reset:
```ts
reset({
preset: 'all',
listReset: false,
videoReset: false,
})
```
## Tailwind CSS v4 用法
在入口 CSS 中通过 `@plugin` 注册即可:
```css title="app.css"
@plugin 'weapp-tailwindcss/reset';
@plugin 'weapp-tailwindcss/reset' ({
preset: 'content',
buttonReset: false,
imageReset: {
selectors: ['.wx-reset-image'],
declarations: {
display: 'inline-block',
},
},
extraResets: [
{
selectors: ['.list-reset'],
declarations: { listStyle: 'none', margin: '0', padding: '0' },
},
],
});
@import 'tailwindcss/utilities';
```
同样可以通过 `buttonReset: false` / `imageReset: false` 精准控制需要的 reset。`preset` 负责批量开启内置规则,`extraResets` 允许你一次性追加多个自定义规则。