vite-plugin-taro 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +83 -106
  2. package/README.zh.md +83 -104
  3. package/dist/node/build-context.d.ts +25 -0
  4. package/dist/node/build-context.js +48 -0
  5. package/dist/node/css/css-pipeline.d.ts +21 -0
  6. package/dist/node/css/css-pipeline.js +129 -0
  7. package/dist/node/plugins/conditional-directives.d.ts +3 -0
  8. package/dist/node/plugins/conditional-directives.js +62 -0
  9. package/dist/node/plugins/taro-runtime.d.ts +5 -0
  10. package/dist/node/plugins/taro-runtime.js +18 -0
  11. package/dist/node/targets/h5/plugin.d.ts +6 -0
  12. package/dist/node/targets/h5/plugin.js +117 -0
  13. package/dist/node/targets/h5/virtual-modules.d.ts +5 -0
  14. package/dist/node/targets/h5/virtual-modules.js +60 -0
  15. package/dist/node/targets/wx/companion-assets.d.ts +19 -0
  16. package/dist/node/targets/wx/companion-assets.js +129 -0
  17. package/dist/node/targets/wx/dev-server/development-session.d.ts +31 -0
  18. package/dist/node/targets/wx/dev-server/development-session.js +202 -0
  19. package/dist/node/targets/wx/dev-server/full-build-scheduler.d.ts +14 -0
  20. package/dist/node/targets/wx/dev-server/full-build-scheduler.js +60 -0
  21. package/dist/node/targets/wx/dev-server/js-utils.d.ts +5 -0
  22. package/dist/node/targets/wx/dev-server/js-utils.js +28 -0
  23. package/dist/node/targets/wx/dev-server/output.d.ts +19 -0
  24. package/dist/node/targets/wx/dev-server/output.js +44 -0
  25. package/dist/node/targets/wx/dev-server/rolldown-runtime-source.d.ts +8 -0
  26. package/dist/node/targets/wx/dev-server/rolldown-runtime-source.js +95 -0
  27. package/dist/node/targets/wx/dev-server/update-server-state.d.ts +65 -0
  28. package/dist/node/targets/wx/dev-server/update-server-state.js +116 -0
  29. package/dist/node/targets/wx/dev-server/update-transport.d.ts +28 -0
  30. package/dist/node/targets/wx/dev-server/update-transport.js +212 -0
  31. package/dist/node/targets/wx/dev-server/vite-bundled-dev-adapter.d.ts +44 -0
  32. package/dist/node/targets/wx/dev-server/vite-bundled-dev-adapter.js +145 -0
  33. package/dist/node/targets/wx/development-files.d.ts +8 -0
  34. package/dist/node/targets/wx/development-files.js +8 -0
  35. package/dist/node/targets/wx/plugin.d.ts +6 -0
  36. package/dist/node/targets/wx/plugin.js +143 -0
  37. package/dist/node/targets/wx/react-refresh.d.ts +4 -0
  38. package/dist/node/targets/wx/react-refresh.js +38 -0
  39. package/dist/node/targets/wx/virtual-modules.d.ts +16 -0
  40. package/dist/node/targets/wx/virtual-modules.js +120 -0
  41. package/dist/node/utils/async.d.ts +8 -0
  42. package/dist/node/utils/async.js +16 -0
  43. package/dist/node/utils/filesystem.d.ts +13 -0
  44. package/dist/node/utils/filesystem.js +43 -0
  45. package/dist/{vite/utils.d.ts → node/utils/modules.d.ts} +2 -2
  46. package/dist/{vite/utils.js → node/utils/modules.js} +10 -3
  47. package/dist/node/utils/packages.d.ts +2 -0
  48. package/dist/node/utils/packages.js +8 -0
  49. package/dist/node/vite-plugin.d.ts +4 -0
  50. package/dist/node/vite-plugin.js +33 -0
  51. package/dist/options.d.ts +21 -0
  52. package/dist/{shim/h5.d.ts → runtime/h5/taro-runtime.d.ts} +3 -1
  53. package/dist/runtime/h5/taro-runtime.js +9 -0
  54. package/dist/runtime/taro/api.d.ts +5 -0
  55. package/dist/{virtual → runtime/taro}/api.js +3 -0
  56. package/dist/runtime/taro/components.d.ts +2 -0
  57. package/dist/runtime/taro/components.js +2 -0
  58. package/dist/runtime/wx/page-update.d.ts +6 -0
  59. package/dist/runtime/wx/page-update.js +157 -0
  60. package/dist/{shim/wx.d.ts → runtime/wx/taro-runtime.d.ts} +1 -0
  61. package/dist/{shim/wx.js → runtime/wx/taro-runtime.js} +1 -0
  62. package/dist/runtime/wx/update-client-state.d.ts +68 -0
  63. package/dist/runtime/wx/update-client-state.js +84 -0
  64. package/dist/runtime/wx/update-client.d.ts +1 -0
  65. package/dist/runtime/wx/update-client.js +170 -0
  66. package/dist/vite.d.ts +2 -2
  67. package/dist/vite.js +1 -1
  68. package/package.json +15 -11
  69. package/src/node/build-context.ts +63 -0
  70. package/src/node/css/css-pipeline.ts +147 -0
  71. package/src/node/plugins/conditional-directives.ts +76 -0
  72. package/src/node/plugins/taro-runtime.ts +22 -0
  73. package/src/node/targets/h5/plugin.ts +135 -0
  74. package/src/node/targets/h5/virtual-modules.ts +71 -0
  75. package/src/node/targets/wx/companion-assets.ts +170 -0
  76. package/src/node/targets/wx/dev-server/development-session.ts +253 -0
  77. package/src/node/targets/wx/dev-server/full-build-scheduler.ts +62 -0
  78. package/src/node/targets/wx/dev-server/js-utils.ts +33 -0
  79. package/src/node/targets/wx/dev-server/output.ts +56 -0
  80. package/src/node/targets/wx/dev-server/rolldown-runtime-source.ts +95 -0
  81. package/src/node/targets/wx/dev-server/update-server-state.ts +183 -0
  82. package/src/node/targets/wx/dev-server/update-transport.ts +261 -0
  83. package/src/node/targets/wx/dev-server/vite-bundled-dev-adapter.ts +203 -0
  84. package/src/node/targets/wx/development-files.ts +11 -0
  85. package/src/node/targets/wx/plugin.ts +163 -0
  86. package/src/node/targets/wx/react-refresh.ts +51 -0
  87. package/src/node/targets/wx/virtual-modules.ts +152 -0
  88. package/src/node/utils/async.ts +19 -0
  89. package/src/node/utils/filesystem.ts +45 -0
  90. package/src/{vite/utils.ts → node/utils/modules.ts} +11 -3
  91. package/src/node/utils/packages.ts +10 -0
  92. package/src/node/vite-plugin.ts +41 -0
  93. package/src/options.ts +25 -0
  94. package/src/runtime/h5/taro-css.d.ts +3 -0
  95. package/src/runtime/h5/taro-runtime.ts +10 -0
  96. package/src/{virtual → runtime/taro}/api.ts +3 -0
  97. package/src/runtime/taro/components.ts +2 -0
  98. package/src/runtime/wx/page-update.ts +230 -0
  99. package/src/runtime/wx/react-refresh.d.ts +20 -0
  100. package/src/{shim/wx.ts → runtime/wx/taro-runtime.ts} +1 -0
  101. package/src/runtime/wx/update-client-state.ts +138 -0
  102. package/src/runtime/wx/update-client.ts +222 -0
  103. package/src/vite.ts +2 -2
  104. package/dist/shim/h5.js +0 -5
  105. package/dist/virtual/api.d.ts +0 -3
  106. package/dist/virtual/components.d.ts +0 -1
  107. package/dist/virtual/components.js +0 -1
  108. package/dist/vite/constants.d.ts +0 -4
  109. package/dist/vite/constants.js +0 -8
  110. package/dist/vite/plugins.d.ts +0 -8
  111. package/dist/vite/plugins.js +0 -186
  112. package/dist/vite/tailwindcss.d.ts +0 -3
  113. package/dist/vite/tailwindcss.js +0 -35
  114. package/dist/vite/targets/h5.d.ts +0 -31
  115. package/dist/vite/targets/h5.js +0 -201
  116. package/dist/vite/targets/wx.d.ts +0 -74
  117. package/dist/vite/targets/wx.js +0 -362
  118. package/dist/vite/types.d.ts +0 -38
  119. package/dist/vite/virtual-modules.d.ts +0 -3
  120. package/dist/vite/virtual-modules.js +0 -13
  121. package/dist/vite/vite-plugin-taro.d.ts +0 -7
  122. package/dist/vite/vite-plugin-taro.js +0 -80
  123. package/src/shim/h5.ts +0 -6
  124. package/src/virtual/components.ts +0 -1
  125. package/src/vite/constants.ts +0 -12
  126. package/src/vite/plugins.ts +0 -218
  127. package/src/vite/tailwindcss.ts +0 -41
  128. package/src/vite/targets/h5.ts +0 -229
  129. package/src/vite/targets/wx.ts +0 -436
  130. package/src/vite/types.ts +0 -48
  131. package/src/vite/virtual-modules.ts +0 -14
  132. package/src/vite/vite-plugin-taro.ts +0 -106
  133. /package/dist/{vite/types.js → options.js} +0 -0
package/README.zh.md CHANGED
@@ -6,20 +6,21 @@
6
6
 
7
7
  简体中文 | [English](README.md)
8
8
 
9
- 使用最新标准化前端技术栈 Vite 8、React 19 和 Tailwind CSS v4 构建微信小程序。
9
+ 使用最新标准化前端技术栈 Vite 8、React 19、Taro 4 和 Tailwind CSS v4 构建微信小程序与 Web 应用。
10
10
 
11
- `vite-plugin-taro` 适用于希望使用 Taro 跨平台 React 组件和 API,但更偏好 Vite 而非 Taro webpack 的应用。你只需要这个插件,就能构建完整的微信小程序。
11
+
12
+ `vite-plugin-taro` 面向希望用 Vite 构建 Taro React 应用的团队:保留 Taro 跨平台组件和 API,告别 Taro webpack,并修复/规避官方 Taro Vite 的常见坑。一个插件即可构建微信小程序与 Web。
12
13
 
13
14
  在线演示:<https://sep2.github.io/vite-plugin-taro>。如何在本地运行,请参见[示例应用](https://github.com/sep2/vite-plugin-taro/tree/main/packages/loan-genius/README.zh.md)。
14
15
 
15
- - **原生 Vite 构建** 使用标准 Vite 8 配置,无需维护老旧的 webpack 配置,并支持所有 Vite 插件。
16
- - **热更新** 微信小程序与 H5 都支持开发模式 watch,基于 Vite 8 热更新/快速重建即时预览。
17
- - **依托成熟 Taro 能力** 复用久经实战检验的 Taro API 和组件,完整使用 Taro 跨端能力。
18
- - **Tailwind 就绪** 内置 Tailwind CSS v4 支持,微信小程序与 H5 样式开箱即用。
19
- - **条件编译** 支持 Taro 风格 `#ifdef` / `#ifndef` / `#if`,可按微信 / Web 裁剪代码和样式。
20
- - **工作区友好** 支持普通项目与 monorepo,兼容 npm、pnpm、Yarn、Bun 等包管理器。
21
- - **类型友好** 项目全链路支持 TypeScript。
22
- - **微信 Skyline** 支持微信小程序 Skyline 渲染模式输出。
16
+ - **Vite 8 + React 19** 基于 Vite 生态,一份代码覆盖微信小程序与 Web。
17
+ - **热更新** 基于 Vite 重构的热更新,微信小程序完美支持,页面编辑不再丢失状态。
18
+ - **Tailwind CSS v4 开箱即用** 直接书写工具类,微信与 Web 样式自动适配。
19
+ - **基于 Taro,超越 Taro** 使用 Taro 组件和 API,摆脱旧式 webpack 链路。
20
+ - **Skyline 就绪** 支持微信 Skyline 渲染模式。
21
+ - **条件编译** Taro 风格 `#ifdef` / `#ifndef` 条件块拆分代码和样式。
22
+ - **工作区友好** 支持普通项目与 monorepo,兼容 `npm`、`pnpm`、`Yarn`、`Bun`。
23
+ - **TypeScript 友好** 从配置到应用代码都有类型支持。
23
24
 
24
25
  ## 快速开始
25
26
 
@@ -31,6 +32,9 @@
31
32
  # 使用默认模板创建新应用
32
33
  npm create vite-taro@latest my-app
33
34
 
35
+ # 或使用 pnpm 创建
36
+ pnpm --config.minimum-release-age=0 create vite-taro@latest my-app
37
+
34
38
  # 进入项目并安装依赖
35
39
  cd my-app
36
40
  npm install
@@ -43,7 +47,7 @@ npm install
43
47
  ### 3. 开发模式运行
44
48
 
45
49
  ```sh
46
- # 微信小程序:以 watch 模式重新构建 dist/wx
50
+ # 微信小程序:启动 Vite 热更新开发模式
47
51
  npm run dev:wx
48
52
 
49
53
  # 然后在微信开发者工具中打开 dist/wx
@@ -57,7 +61,7 @@ npm run dev:h5
57
61
 
58
62
  你可以在两个终端中同时运行 `npm run dev:wx` 和 `npm run dev:h5`。
59
63
 
60
- 提示:受微信限制,开发者工具热重载有时不会完整生效。建议日常优先使用 H5 Vite 热更新快速调试,并定期在微信开发者工具中验证小程序端效果。
64
+ 微信开发模式通过 Rolldown 增量模块图和 React Refresh 完整支持 Vite 热更新。JavaScript 修改会保留当前原生页面及 React/输入状态;CSS、资源、public 文件和配置修改会自动重新构建。
61
65
 
62
66
  ### 4. 构建、预览和类型检查
63
67
 
@@ -109,7 +113,7 @@ npm install react react-dom
109
113
  npm install -D vite typescript@rc @types/node @types/react @types/react-dom cross-env
110
114
  ```
111
115
 
112
- 你不应再直接依赖任何 `@tarojs/*` 包。如果已经依赖,请将它们移除。
116
+ 请从 `dependencies` 和 `devDependencies` 中移除所有 `@tarojs/*` 包。
113
117
 
114
118
  下面的步骤会创建如下源码结构:
115
119
 
@@ -172,19 +176,9 @@ export default defineConfig(({ mode }) => {
172
176
  vitePluginTaro({
173
177
  target,
174
178
  app: 'src/app.ts',
175
- pages: [
176
- {
177
- path: 'pages/index/index',
178
- config: {
179
- navigationBarTitleText: 'Home'
180
- }
181
- }
182
- ],
179
+ pages: [{ path: 'pages/index/index', config: { navigationBarTitleText: 'Home' } }],
183
180
  appJson: {
184
- window: {
185
- navigationBarTitleText: 'Demo',
186
- navigationBarBackgroundColor: '#ffffff'
187
- }
181
+ window: { navigationBarTitleText: 'Demo' }
188
182
  },
189
183
  projectConfigJson: {
190
184
  appid: env.VITE_PLUGIN_TARO_WECHAT_APP_ID || 'touristappid',
@@ -206,6 +200,7 @@ export default defineConfig(({ mode }) => {
206
200
  - `app` 是 React 根应用组件模块,应默认导出应用组件。
207
201
  - 每个 `pages[].path` 都会映射到 `src/${path}.tsx` 文件。例如,`pages/index/index` 需要 `src/pages/index/index.tsx`。
208
202
  - `appJson.pages` 会根据 `pages` 自动生成;你在 `appJson` 中传入的任何 `pages` 字段都会被覆盖。
203
+ - 如果应用使用 Skyline,请添加相关的 `appJson` 和 `projectConfigJson` 配置。
209
204
  - 插件不会读取 Taro CLI 配置文件,例如 `config/index.ts`、`app.config.ts` 或页面 `config.ts` 文件。请通过插件选项传入应用和页面配置。
210
205
 
211
206
  ### 3. 创建应用组件
@@ -213,75 +208,62 @@ export default defineConfig(({ mode }) => {
213
208
  `src/app.ts` 是共享应用包装组件。它会通过 `children` 接收当前页面。
214
209
 
215
210
  ```tsx
216
- import Taro from 'virtual:taro/api'
217
211
  import type { PropsWithChildren } from 'react'
218
212
  import './app.css'
219
213
 
220
- function App({ children }: PropsWithChildren) {
221
- Taro.useLaunch(() => {
222
- console.log('App launched')
223
- })
224
-
214
+ export default function App({ children }: PropsWithChildren) {
225
215
  return children
226
216
  }
217
+ ```
218
+
219
+ 请在应用组件中导入全局样式。下一步会创建 `src/app.css`。
220
+
221
+ ### 4. 创建全局样式
222
+
223
+ `src/app.css` 可以使用普通 CSS,也可以配合组件内 CSS Modules 和 Tailwind CSS v4。插件会自动注入 Taro H5 组件样式;默认全局样式会为两个目标启用 Tailwind CSS v4:
224
+
225
+ ```css
226
+ @import "tailwindcss/theme.css";
227
+ @import "tailwindcss/preflight.css";
228
+ @import "tailwindcss/utilities.css";
227
229
 
228
- export default App
230
+ @source "./";
229
231
  ```
230
232
 
231
- 请在应用组件中导入全局样式。微信构建会将它们收集到 `app.wxss`,H5 输出也会包含它们。
233
+ 请保留 `@source "./";`,让 Tailwind 扫描源码目录。
232
234
 
233
- ### 4. 创建页面组件
235
+ ### 5. 创建页面组件
234
236
 
235
237
  `src/pages/index/index.tsx` 是 `pages/index/index` 对应的 React 页面组件。
236
238
 
237
239
  ```tsx
238
- import Taro from 'virtual:taro/api'
239
- import { Button, Text, View } from 'virtual:taro/components'
240
+ import { Text, View } from 'virtual:taro/components'
240
241
 
241
242
  export default function IndexPage() {
242
- const windowInfo = Taro.getWindowInfo()
243
-
244
243
  return (
245
244
  <View className="p-4">
246
- <Text>Viewport width: {windowInfo.windowWidth}</Text>
247
- <Button
248
- onClick={() => {
249
- Taro.showToast({ title: 'Hello from Taro' })
250
- }}
251
- >
252
- Show toast
253
- </Button>
245
+ <Text>Hello Taro</Text>
254
246
  </View>
255
247
  )
256
248
  }
257
249
  ```
258
250
 
259
- ### 5. 添加 H5 HTML 外壳
251
+ ### 6. 添加 H5 HTML 外壳
260
252
 
261
253
  对于 H5,请保留一个普通的 Vite `index.html`,并包含 `#app` 挂载节点。插件会自动注入生成的 Taro H5 入口,因此你不需要普通 Vite 的 `src/main.tsx` 脚本。
262
254
 
263
255
  ```html
264
- <!doctype html>
265
- <html lang="en">
266
- <head>
267
- <meta charset="UTF-8" />
268
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
269
- <title>Taro Vite App</title>
270
- </head>
271
- <body>
272
- <div id="app"></div>
273
- </body>
274
- </html>
256
+ <div id="app"></div>
275
257
  ```
276
258
 
277
- ### 6. 添加脚本
259
+ ### 7. 添加脚本
278
260
 
279
261
  使用与 `create-vite-taro` 生成项目一致的脚本:
280
262
 
281
263
  ```json
282
264
  {
283
265
  "scripts": {
284
- "dev:wx": "cross-env NODE_ENV=development VITE_PLUGIN_TARO_TARGET=wx vite build --watch",
266
+ "dev:wx": "cross-env NODE_ENV=development VITE_PLUGIN_TARO_TARGET=wx vite",
285
267
  "dev:h5": "cross-env NODE_ENV=development VITE_PLUGIN_TARO_TARGET=h5 vite",
286
268
  "build:wx": "cross-env NODE_ENV=production VITE_PLUGIN_TARO_TARGET=wx vite build",
287
269
  "build:h5": "cross-env NODE_ENV=production VITE_PLUGIN_TARO_TARGET=h5 vite build",
@@ -291,11 +273,11 @@ export default function IndexPage() {
291
273
  }
292
274
  ```
293
275
 
294
- ### 7. 运行每个目标
276
+ ### 8. 运行每个目标
295
277
 
296
278
  ```sh
297
- npm run dev:wx # 以 watch 模式重新构建 dist/wx
298
- npm run dev:h5 # 启动 H5 开发服务器
279
+ npm run dev:wx # 启动微信小程序热更新开发模式
280
+ npm run dev:h5 # 启动 Web 开发服务器
299
281
  npm run build:wx # 构建 dist/wx
300
282
  npm run build:h5 # 构建 dist/h5
301
283
  npm run preview:h5 # 预览 dist/h5
@@ -304,6 +286,8 @@ npm run typecheck # 使用 tsc 进行类型检查
304
286
 
305
287
  在微信开发者工具中打开生成的 `dist/wx` 目录。
306
288
 
289
+ 微信开发模式会在 Vite 报告就绪前,预先完整构建 App 和所有已配置页面。JavaScript 和 TypeScript 组件修改通过 React Refresh 更新,并保留兼容的 React 状态、当前 Taro 页面以及原生输入状态。每次代码更新都会重置模块内部状态。修改 CSS、资源或应用配置时,会有意执行完整构建并让开发者工具重新加载。插件会自动为生成的开发项目启用微信的 `compileHotReLoad` 设置。
290
+
307
291
  | 目标 | 含义 | 输出目录 |
308
292
  | --- | --- | --- |
309
293
  | `wx` | 开发/生产模式下的微信小程序。 | `dist/wx` |
@@ -333,29 +317,13 @@ type VitePluginTaroOptions = {
333
317
  | --- | --- |
334
318
  | `target` | 本次 Vite 调用的活动目标。微信小程序使用 `wx`,Web 使用 `h5`。 |
335
319
  | `app` | 默认导出根 React 应用组件的源码文件,例如 `src/app.ts` 或 `src/app.tsx`。 |
336
- | `pages` | 有序页面列表。该顺序会成为 `app.json.pages` 和 H5 路由顺序。 |
320
+ | `pages` | 有序页面列表。该顺序会成为 `app.json.pages` 和 Web 路由顺序。 |
337
321
  | `pages[].path` | 不带扩展名的 Taro 风格路由和输出路径,例如 `pages/index/index`。页面组件必须存在于 `src/${path}.tsx`。 |
338
- | `pages[].config` | 合并到生成的微信页面 JSON 和 H5 路由配置中的页面配置。 |
339
- | `appJson` | 基础应用配置。插件会用 `options.pages` 覆盖其中的 `pages` 字段。 |
322
+ | `pages[].config` | 合并到生成的微信页面 JSON 和 Web 路由配置中的页面配置。 |
323
+ | `appJson` | 两个目标共享的基础应用配置。插件会用 `options.pages` 覆盖其中的 `pages` 字段。 |
340
324
  | `projectConfigJson` | `wx` 构建时输出的微信 `project.config.json` 内容。即使当前目标是 `h5`,选项类型也要求提供它。 |
341
325
  | `sitemapJson` | `wx` 构建时输出的微信 `sitemap.json` 内容。即使当前目标是 `h5`,选项类型也要求提供它。 |
342
326
 
343
- ## 样式
344
-
345
- 你可以使用普通 CSS、CSS Modules 或 Tailwind CSS v4。
346
-
347
- 对于 Tailwind CSS v4,请从全局 CSS 文件(例如 `src/app.css`)导入 Tailwind:
348
-
349
- ```css
350
- @import "tailwindcss/theme.css";
351
- @import "tailwindcss/preflight.css";
352
- @import "tailwindcss/utilities.css";
353
-
354
- @source "./";
355
- ```
356
-
357
- 插件会为 `wx` 构建注册 `weapp-tailwindcss`,并为 `h5` 构建注册 `@tailwindcss/vite`。对于 `wx`,Vite 输出的 CSS 会被收集到 `app.wxss`,并为每个页面生成配套的 `.wxss` 文件。
358
-
359
327
  ## 条件编译
360
328
 
361
329
  插件会在 Vite 解析源码前移除未激活的 Taro 风格条件注释块。它适用于 `node_modules` 之外的 TypeScript、JavaScript、JSX/TSX、CSS、Sass、Less 和 Stylus 文件。
@@ -369,16 +337,14 @@ console.log('WeChat only')
369
337
  console.log('H5 only')
370
338
  // #endif
371
339
 
372
- // #if wx && !h5
373
- console.log('WeChat expression')
374
- // #elif h5
375
- console.log('H5 expression')
340
+ // #ifndef h5
341
+ console.log(' H5')
376
342
  // #else
377
- console.log('fallback')
343
+ console.log('H5 fallback')
378
344
  // #endif
379
345
  ```
380
346
 
381
- 支持的指令包括 `#ifdef`、`#ifndef`、`#if`、`#elif`、`#else` 和 `#endif`。条件使用插件目标标记 `wx` 和 `h5`;`#if` 表达式支持 `!`、`&&` 和 `||`。
347
+ 支持的指令包括 `#ifdef`、`#ifndef`、`#else` 和 `#endif`。条件使用插件目标标记 `wx` 和 `h5`。
382
348
 
383
349
  ## 按目标输出
384
350
 
@@ -405,9 +371,9 @@ dist/wx/
405
371
 
406
372
  请使用微信开发者工具打开 `dist/wx`;不要打开源码项目目录。
407
373
 
408
- ### H5
374
+ ### H5 / Web
409
375
 
410
- 对于 `target: 'h5'`,插件会向 `index.html` 注入生成模块,导入 Taro H5 组件样式,根据 `pages` 构建路由记录,并使用 Taro 的 hash-history 路由挂载应用。路由使用配置中的页面路径,例如 `#/pages/index/index`。
376
+ 对于 `target: 'h5'`,插件会向 `index.html` 注入生成模块,在应用之前导入 Taro H5 组件样式,根据 `pages` 构建路由记录,并使用 Taro 的 hash-history 路由挂载应用。路由使用配置中的页面路径,例如 `#/pages/index/index`。
411
377
 
412
378
  ## 从 Taro 迁移
413
379
 
@@ -420,7 +386,9 @@ dist/wx/
420
386
  3. 在 `pages` 中注册每个页面。每个页面路径都必须匹配 `src/${path}.tsx`。
421
387
  4. 将 Taro 脚本替换为设置 `VITE_PLUGIN_TARO_TARGET=wx` 或 `VITE_PLUGIN_TARO_TARGET=h5` 的 Vite 脚本。
422
388
  5. 对于 H5,添加普通 Vite `index.html`,其中包含 `<div id="app"></div>`,且不要添加单独的 `src/main.tsx` 入口。
423
- 6. 将应用代码中的 `@tarojs/*` 导入替换为插件虚拟模块。
389
+ 6. 将全局样式迁移到 `src/app.css`,在 app 入口保留 `import './app.css'`,并按下方示例添加 Taro/Tailwind 导入。
390
+ 7. 从 `dependencies` 和 `devDependencies` 中移除所有 `@tarojs/*` 包。
391
+ 8. 将应用代码中的 `@tarojs/*` 导入替换为插件虚拟模块。
424
392
 
425
393
  迁移前:
426
394
 
@@ -436,7 +404,17 @@ import Taro from 'virtual:taro/api'
436
404
  import { Text, View } from 'virtual:taro/components'
437
405
  ```
438
406
 
439
- 应用代码中禁止直接导入 `@tarojs/*`。请让插件负责 Taro 运行时解析,使微信和 H5 构建都获得正确的目标特定别名。
407
+ 样式迁移:
408
+
409
+ ```css
410
+ @import "tailwindcss/theme.css";
411
+ @import "tailwindcss/preflight.css";
412
+ @import "tailwindcss/utilities.css";
413
+
414
+ @source "./";
415
+ ```
416
+
417
+ 移除所有 `@tarojs/*` 包,并且不要在应用代码中直接导入它们。请让插件负责 Taro 运行时解析。
440
418
 
441
419
  ## 示例应用
442
420
 
@@ -455,17 +433,17 @@ pnpm prepare:taro
455
433
  pnpm build:plugin
456
434
 
457
435
  # 运行微信示例应用
458
- pnpm dev:sample:wx
436
+ pnpm dev:loan-genius:wx
459
437
 
460
438
  # 将示例应用构建为微信输出
461
- pnpm build:sample:wx
439
+ pnpm build:loan-genius:wx
462
440
 
463
441
  # 以开发模式运行 H5 示例应用
464
- pnpm dev:sample:h5
442
+ pnpm dev:loan-genius:h5
465
443
 
466
444
  # 将示例应用构建为 H5 输出并预览
467
- pnpm build:sample:h5
468
- pnpm preview:sample:h5
445
+ pnpm build:loan-genius:h5
446
+ pnpm preview:loan-genius:h5
469
447
  ```
470
448
 
471
449
  使用微信开发者工具打开 `packages/loan-genius/dist/wx`,以测试小程序输出。
@@ -488,11 +466,11 @@ pnpm typecheck
488
466
  | `pnpm typecheck` | 使用 `tsc` 对插件和示例应用进行类型检查。 |
489
467
  | `pnpm lint` | 运行 Biome 检查。 |
490
468
  | `pnpm format` | 应用 Biome 格式化。 |
491
- | `pnpm dev:sample:wx` | watch 模式构建微信小程序示例。请先构建插件。 |
492
- | `pnpm dev:sample:h5` | 以 Vite 开发模式启动 H5 示例应用。请先构建插件。 |
493
- | `pnpm build:sample:wx` | 将微信小程序示例构建到 `packages/loan-genius/dist/wx`。 |
494
- | `pnpm build:sample:h5` | 将 H5 示例应用构建到 `packages/loan-genius/dist/h5`。 |
495
- | `pnpm preview:sample:h5` | 预览构建后的 H5 示例。 |
469
+ | `pnpm dev:loan-genius:wx` | 启动支持热更新的微信小程序示例。请先构建插件。 |
470
+ | `pnpm dev:loan-genius:h5` | 以 Vite 开发模式启动 H5 示例应用。请先构建插件。 |
471
+ | `pnpm build:loan-genius:wx` | 将微信小程序示例构建到 `packages/loan-genius/dist/wx`。 |
472
+ | `pnpm build:loan-genius:h5` | 将 H5 示例应用构建到 `packages/loan-genius/dist/h5`。 |
473
+ | `pnpm preview:loan-genius:h5` | 预览构建后的 H5 示例。 |
496
474
  | `pnpm changelog` | 从 git release tag 重新生成 `CHANGELOG.md`。 |
497
475
  | `pnpm publish:dry` | 干运行包校验和发布流程。 |
498
476
  | `pnpm release <version\|bump>` | 验证发布、更新版本、更新 changelog、创建 release commit 和 tag,并推送触发 CI 发布。 |
@@ -500,6 +478,7 @@ pnpm typecheck
500
478
 
501
479
  ## 限制
502
480
 
481
+ - 目前只支持 React 应用。
503
482
  - 目前只生成 `wx` 和 `h5` 目标。
504
483
  - 应用代码不能直接导入 `@tarojs/*` 包。
505
484
 
@@ -513,8 +492,8 @@ pnpm typecheck
513
492
  | 微信开发者工具无法打开应用 | 打开生成的 `dist/wx` 文件夹,并检查 `projectConfigJson.appid`。 |
514
493
  | H5 显示空白页 | 确保 `index.html` 中保留 `<div id="app"></div>`,已注册插件,并避免添加单独的默认 Vite `main.tsx` 入口。 |
515
494
  | Taro API 缺失或行为不同 | 移除应用代码中直接导入的 `@tarojs/*`,并从 `virtual:taro/api` 导入 Taro。 |
516
- | 组件在 H5 上渲染时缺少预期样式 | `virtual:taro/components` 导入组件,并确保 `h5` 目标启用了插件。 |
517
- | Tailwind 类没有生效 | 确保全局 CSS 导入 Tailwind,并包含覆盖源码文件的 `@source` 路径。 |
495
+ | 组件在 H5 上渲染时缺少预期样式 | 确保 app 入口导入了 `./app.css`,并且生成的 H5 入口已注入到 `index.html`。 |
496
+ | Tailwind 类没有生效 | 确保 `src/app.css` 导入了 Tailwind CSS 文件,保留 `@source "./";`,并且类名可以被静态扫描到。移动文件后请重启开发服务。 |
518
497
 
519
498
  ## 发布流程
520
499
 
@@ -0,0 +1,25 @@
1
+ import type { ConfigEnv, ResolvedConfig } from 'vite';
2
+ import type { JsonObject, VitePluginTaroOptions, VitePluginTaroPageOption, VitePluginTaroTarget } from '../options.ts';
3
+ import { CssPipeline } from './css/css-pipeline.ts';
4
+ type ProjectContext = Readonly<{
5
+ target: VitePluginTaroTarget;
6
+ appComponentFile: string;
7
+ pages: readonly VitePluginTaroPageOption[];
8
+ appConfig: JsonObject;
9
+ projectConfigJson: JsonObject;
10
+ projectPrivateConfigJson?: JsonObject;
11
+ sitemapJson: JsonObject;
12
+ }>;
13
+ /** Owns the shared project, Vite lifecycle state, and cross-target services for one build. */
14
+ export declare class BuildContext {
15
+ readonly project: ProjectContext;
16
+ readonly css: CssPipeline;
17
+ private developmentMode;
18
+ private resolvedViteConfig;
19
+ constructor(options: VitePluginTaroOptions);
20
+ configure(environment: ConfigEnv): void;
21
+ resolve(config: ResolvedConfig): void;
22
+ get development(): boolean;
23
+ get vite(): ResolvedConfig;
24
+ }
25
+ export {};
@@ -0,0 +1,48 @@
1
+ import path from 'node:path';
2
+ import { CssPipeline } from './css/css-pipeline.js';
3
+ /** Owns the shared project, Vite lifecycle state, and cross-target services for one build. */
4
+ export class BuildContext {
5
+ project;
6
+ css;
7
+ developmentMode;
8
+ resolvedViteConfig;
9
+ constructor(options) {
10
+ this.project = {
11
+ target: options.target,
12
+ appComponentFile: path.resolve(options.app),
13
+ pages: options.pages,
14
+ appConfig: {
15
+ ...options.appJson,
16
+ pages: options.pages.map((page) => page.path)
17
+ },
18
+ projectConfigJson: options.projectConfigJson,
19
+ projectPrivateConfigJson: options.projectPrivateConfigJson,
20
+ sitemapJson: options.sitemapJson
21
+ };
22
+ this.css = new CssPipeline(options.target);
23
+ }
24
+ configure(environment) {
25
+ if (this.developmentMode !== undefined)
26
+ throw new Error('vite-plugin-taro build context was already configured.');
27
+ this.developmentMode = environment.command === 'serve';
28
+ }
29
+ resolve(config) {
30
+ if (this.developmentMode === undefined) {
31
+ throw new Error('vite-plugin-taro build context resolved before it was configured.');
32
+ }
33
+ if (this.resolvedViteConfig)
34
+ throw new Error('vite-plugin-taro build context was already resolved.');
35
+ this.resolvedViteConfig = config;
36
+ this.css.resolve(config.root);
37
+ }
38
+ get development() {
39
+ if (this.developmentMode === undefined)
40
+ throw new Error('vite-plugin-taro build context is not configured.');
41
+ return this.developmentMode;
42
+ }
43
+ get vite() {
44
+ if (!this.resolvedViteConfig)
45
+ throw new Error('vite-plugin-taro build context is not resolved.');
46
+ return this.resolvedViteConfig;
47
+ }
48
+ }
@@ -0,0 +1,21 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { VitePluginTaroTarget } from '../../options.ts';
3
+ type CssTransformResult = {
4
+ code: string;
5
+ map: null;
6
+ };
7
+ /** Owns CSS generation and the class-name state shared by normal chunks and literal WX patches. */
8
+ export declare class CssPipeline {
9
+ readonly plugin: Plugin;
10
+ private readonly target;
11
+ private readonly runtimeClassSet;
12
+ private projectRoot;
13
+ private wxContext;
14
+ constructor(target: VitePluginTaroTarget);
15
+ resolve(projectRoot: string): void;
16
+ transformWxClassNames(code: string, filename: string): Promise<CssTransformResult>;
17
+ private createPlugin;
18
+ private getProjectRoot;
19
+ private getWxContext;
20
+ }
21
+ export {};
@@ -0,0 +1,129 @@
1
+ import path from 'node:path';
2
+ import { createContext } from 'weapp-tailwindcss/core';
3
+ import { createWeappTailwindcssGenerator, resolveTailwindV4Source } from 'weapp-tailwindcss/generator';
4
+ import { normalizeModuleId } from '../utils/modules.js';
5
+ const wxStyleOptions = {
6
+ cssCalc: false,
7
+ autoprefixer: false,
8
+ rem2rpx: true,
9
+ px2rpx: true
10
+ };
11
+ /** Owns CSS generation and the class-name state shared by normal chunks and literal WX patches. */
12
+ export class CssPipeline {
13
+ plugin;
14
+ target;
15
+ runtimeClassSet = new Set();
16
+ projectRoot;
17
+ wxContext;
18
+ constructor(target) {
19
+ this.target = target;
20
+ this.plugin = this.createPlugin();
21
+ }
22
+ resolve(projectRoot) {
23
+ if (this.projectRoot)
24
+ throw new Error('vite-plugin-taro CSS pipeline was already resolved.');
25
+ this.projectRoot = projectRoot;
26
+ this.wxContext = this.target === 'wx' ? createWxCssContext(projectRoot) : undefined;
27
+ }
28
+ async transformWxClassNames(code, filename) {
29
+ if (!this.wxContext || this.runtimeClassSet.size === 0)
30
+ return { code, map: null };
31
+ const result = await this.wxContext.transformJs(code, {
32
+ runtimeSet: this.runtimeClassSet,
33
+ filename,
34
+ generateMap: false
35
+ });
36
+ return { code: result.code, map: null };
37
+ }
38
+ createPlugin() {
39
+ const pipeline = this;
40
+ return {
41
+ name: 'vite-plugin-taro:css',
42
+ enforce: 'pre',
43
+ buildStart() {
44
+ pipeline.runtimeClassSet.clear();
45
+ },
46
+ async transform(code, id) {
47
+ if (!isCssModuleId(id) || !shouldGenerateTailwindCss(code))
48
+ return;
49
+ const projectRoot = pipeline.getProjectRoot();
50
+ const cssFile = resolveCssFile(id, projectRoot);
51
+ const cssBase = path.dirname(cssFile);
52
+ const source = await resolveTailwindV4Source({
53
+ projectRoot,
54
+ cwd: projectRoot,
55
+ base: cssBase,
56
+ css: code,
57
+ cssSources: [{ file: cssFile, base: cssBase, css: code, dependencies: [cssFile] }]
58
+ });
59
+ const generator = createWeappTailwindcssGenerator(source);
60
+ const generated = await generator.generate({
61
+ target: pipeline.target === 'wx' ? 'weapp' : 'web',
62
+ scanSources: true,
63
+ candidates: [],
64
+ styleOptions: pipeline.target === 'wx' ? wxStyleOptions : undefined
65
+ });
66
+ for (const className of generated.classSet)
67
+ pipeline.runtimeClassSet.add(className);
68
+ for (const dependency of generated.dependencies)
69
+ this.addWatchFile(dependency);
70
+ return generated.css;
71
+ },
72
+ async renderChunk(code, chunk) {
73
+ if (pipeline.target !== 'wx')
74
+ return;
75
+ return await pipeline.transformWxClassNames(code, chunk.fileName);
76
+ },
77
+ async generateBundle(_, bundle) {
78
+ if (pipeline.target !== 'wx')
79
+ return;
80
+ const core = pipeline.getWxContext();
81
+ await Promise.all(Object.entries(bundle).map(async ([fileName, item]) => {
82
+ if (item.type === 'asset' && fileName.endsWith('.css')) {
83
+ await transformWxssAsset(core, item);
84
+ }
85
+ }));
86
+ }
87
+ };
88
+ }
89
+ getProjectRoot() {
90
+ if (!this.projectRoot)
91
+ throw new Error('vite-plugin-taro CSS pipeline was used before configuration resolved.');
92
+ return this.projectRoot;
93
+ }
94
+ getWxContext() {
95
+ if (!this.wxContext)
96
+ throw new Error('vite-plugin-taro expected a resolved WeChat CSS pipeline.');
97
+ return this.wxContext;
98
+ }
99
+ }
100
+ function createWxCssContext(projectRoot) {
101
+ return createContext({
102
+ appType: 'taro',
103
+ tailwindcssBasedir: projectRoot,
104
+ generator: { target: 'weapp' },
105
+ ...wxStyleOptions,
106
+ logLevel: 'silent'
107
+ });
108
+ }
109
+ async function transformWxssAsset(core, item) {
110
+ const result = await core.transformWxss(getAssetSource(item), { isMainChunk: true });
111
+ item.source = result.css;
112
+ }
113
+ function shouldGenerateTailwindCss(code) {
114
+ const tailwindEntryImportPattern = /@(import|reference)\s+(?:url\(\s*)?(?:["'])tailwindcss(?:\/(?:theme|preflight|utilities)(?:\.css)?)?(?:["'])/;
115
+ return code.includes('tailwindcss') && tailwindEntryImportPattern.test(code);
116
+ }
117
+ function isCssModuleId(id) {
118
+ return /\.(?:css|scss|sass|less|styl|stylus)(?:$|[?#])/.test(id);
119
+ }
120
+ function getAssetSource(item) {
121
+ if (typeof item.source === 'string')
122
+ return item.source;
123
+ return item.source ? new TextDecoder().decode(item.source) : '';
124
+ }
125
+ function resolveCssFile(id, root) {
126
+ const normalizedId = normalizeModuleId(id);
127
+ const cleanId = normalizedId.startsWith('/@fs/') ? normalizedId.slice('/@fs'.length) : normalizedId;
128
+ return path.isAbsolute(cleanId) ? cleanId : path.resolve(root, cleanId);
129
+ }
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { BuildContext } from '../build-context.ts';
3
+ export declare function createConditionalDirectivePlugin(context: BuildContext): Plugin;
@@ -0,0 +1,62 @@
1
+ import { normalizeModuleId } from '../utils/modules.js';
2
+ export function createConditionalDirectivePlugin(context) {
3
+ return {
4
+ name: 'vite-plugin-taro:conditional-directives',
5
+ enforce: 'pre',
6
+ transform(code, id) {
7
+ if (!isConditionalDirectiveSource(id) || !code.includes('#if'))
8
+ return;
9
+ return { code: transformConditionalDirectives(code, context.project.target), map: null };
10
+ }
11
+ };
12
+ }
13
+ function isConditionalDirectiveSource(id) {
14
+ const normalizedId = normalizeModuleId(id);
15
+ return !normalizedId.includes('/node_modules/') && /\.(?:[cm]?[jt]sx?|css|s[ac]ss|less|styl)$/.test(normalizedId);
16
+ }
17
+ function transformConditionalDirectives(code, target) {
18
+ const lines = code.match(/[^\n]*(?:\n|$)/g) ?? [];
19
+ const frames = [];
20
+ let transformed = '';
21
+ for (const line of lines) {
22
+ if (!line)
23
+ continue;
24
+ const directive = parseDirective(line);
25
+ const lineEnding = line.match(/\r?\n$/)?.[0] ?? '';
26
+ if (!directive) {
27
+ transformed += frames.every((frame) => frame.active) ? line : lineEnding;
28
+ continue;
29
+ }
30
+ if (directive.name === 'ifdef' || directive.name === 'ifndef') {
31
+ const parentActive = frames.every((frame) => frame.active);
32
+ const targetMatched = directive.target.toLowerCase() === target;
33
+ const matched = directive.name === 'ifdef' ? targetMatched : !targetMatched;
34
+ frames.push({ parentActive, matched, active: parentActive && matched });
35
+ }
36
+ else if (directive.name === 'else') {
37
+ const frame = frames.at(-1);
38
+ if (frame)
39
+ frame.active = frame.parentActive && !frame.matched;
40
+ }
41
+ else {
42
+ frames.pop();
43
+ }
44
+ transformed += lineEnding;
45
+ }
46
+ return transformed;
47
+ }
48
+ function parseDirective(line) {
49
+ const match = line.match(/^\s*(?:(?:\/\/)|(?:\/\*))\s*#(ifdef|ifndef|if|elif|else|endif)\b([^*\r\n]*)/);
50
+ if (!match)
51
+ return;
52
+ const name = match[1];
53
+ if (name === 'if' || name === 'elif') {
54
+ throw new Error(`vite-plugin-taro no longer supports #${name}; use #ifdef, #ifndef, or #else.`);
55
+ }
56
+ if (name !== 'ifdef' && name !== 'ifndef' && name !== 'else' && name !== 'endif')
57
+ return;
58
+ return {
59
+ name,
60
+ target: match[2]?.replace(/\*\/$/, '').trim() ?? ''
61
+ };
62
+ }