vite-plugin-taro 0.3.2 → 0.4.0

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 (260) hide show
  1. package/README.en.md +44 -0
  2. package/README.md +22 -497
  3. package/client.d.ts +9 -0
  4. package/dist/node/plugins/client/client-taro.d.ts +4 -0
  5. package/dist/node/plugins/client/client-taro.js +19 -0
  6. package/dist/node/plugins/client/constant.d.ts +4 -0
  7. package/dist/node/plugins/client/constant.js +4 -0
  8. package/dist/node/plugins/conditional/conditional-directives.d.ts +4 -0
  9. package/dist/node/plugins/{conditional-directives.js → conditional/conditional-directives.js} +27 -11
  10. package/dist/node/plugins/css/plugins.d.ts +4 -0
  11. package/dist/node/plugins/css/plugins.js +84 -0
  12. package/dist/node/plugins/h5/constant.d.ts +2 -0
  13. package/dist/node/plugins/h5/constant.js +3 -0
  14. package/dist/node/plugins/h5/plugins.d.ts +4 -0
  15. package/dist/node/plugins/h5/plugins.js +161 -0
  16. package/dist/node/plugins/h5/resolver/module-resolver.d.ts +14 -0
  17. package/dist/node/plugins/h5/resolver/module-resolver.js +19 -0
  18. package/dist/node/plugins/h5/transform-app.d.ts +10 -0
  19. package/dist/node/plugins/h5/transform-app.js +48 -0
  20. package/dist/node/plugins/wx/dev/dev-host.d.ts +15 -0
  21. package/dist/node/plugins/wx/dev/dev-host.js +352 -0
  22. package/dist/node/plugins/wx/dev/hmr-files.d.ts +28 -0
  23. package/dist/node/plugins/wx/dev/hmr-files.js +34 -0
  24. package/dist/node/plugins/wx/dev/patch-publisher.d.ts +22 -0
  25. package/dist/node/plugins/wx/dev/patch-publisher.js +40 -0
  26. package/dist/node/plugins/wx/dev/plugin.d.ts +7 -0
  27. package/dist/node/plugins/wx/dev/plugin.js +73 -0
  28. package/dist/node/plugins/wx/dev/react-refresh.d.ts +20 -0
  29. package/dist/node/plugins/wx/dev/react-refresh.js +198 -0
  30. package/dist/node/plugins/wx/module.d.ts +45 -0
  31. package/dist/node/plugins/wx/module.js +66 -0
  32. package/dist/node/plugins/wx/native/compile-native-component-interface.d.ts +21 -0
  33. package/dist/node/plugins/wx/native/compile-native-component-interface.js +29 -0
  34. package/dist/node/plugins/wx/native/create-native-component-output.d.ts +15 -0
  35. package/dist/node/plugins/wx/native/create-native-component-output.js +39 -0
  36. package/dist/node/plugins/wx/native/native-component-assets.d.ts +26 -0
  37. package/dist/node/plugins/wx/native/native-component-assets.js +76 -0
  38. package/dist/node/plugins/wx/native/native-component-interface.d.ts +12 -0
  39. package/dist/node/plugins/wx/native/native-component-interface.js +201 -0
  40. package/dist/node/plugins/wx/output/files.d.ts +12 -0
  41. package/dist/node/plugins/wx/output/files.js +12 -0
  42. package/dist/node/plugins/wx/output/json.d.ts +14 -0
  43. package/dist/node/plugins/wx/output/json.js +52 -0
  44. package/dist/node/plugins/wx/output/relative-root.d.ts +2 -0
  45. package/dist/node/plugins/wx/output/relative-root.js +6 -0
  46. package/dist/node/plugins/wx/output/templates.d.ts +7 -0
  47. package/dist/node/plugins/wx/output/templates.js +100 -0
  48. package/dist/node/plugins/wx/placement/placer.d.ts +78 -0
  49. package/dist/node/plugins/wx/placement/placer.js +145 -0
  50. package/dist/node/plugins/wx/placement/plan.d.ts +46 -0
  51. package/dist/node/plugins/wx/placement/plan.js +210 -0
  52. package/dist/node/plugins/wx/plugins.d.ts +4 -0
  53. package/dist/node/plugins/wx/plugins.js +137 -0
  54. package/dist/node/plugins/wx/render/capsule-wrapper.d.ts +3 -0
  55. package/dist/node/plugins/wx/render/capsule-wrapper.js +64 -0
  56. package/dist/node/plugins/wx/render/capsule.d.ts +4 -0
  57. package/dist/node/plugins/wx/render/capsule.js +13 -0
  58. package/dist/node/plugins/wx/render/native.d.ts +9 -0
  59. package/dist/node/plugins/wx/render/native.js +45 -0
  60. package/dist/node/plugins/wx/render/transport.d.ts +17 -0
  61. package/dist/node/plugins/wx/render/transport.js +94 -0
  62. package/dist/node/plugins/wx/resolve/resolver.d.ts +7 -0
  63. package/dist/node/plugins/wx/resolve/resolver.js +86 -0
  64. package/dist/node/plugins/wx/resolve/specialize-bootstrap.d.ts +9 -0
  65. package/dist/node/plugins/wx/resolve/specialize-bootstrap.js +9 -0
  66. package/dist/node/plugins/wx/resolve/specialize-page-capsule.d.ts +9 -0
  67. package/dist/node/plugins/wx/resolve/specialize-page-capsule.js +11 -0
  68. package/dist/node/utils/constant.d.ts +1 -0
  69. package/dist/node/utils/constant.js +1 -0
  70. package/dist/node/utils/memoize.d.ts +122 -0
  71. package/dist/node/utils/memoize.js +86 -0
  72. package/dist/node/utils/modules.d.ts +20 -24
  73. package/dist/node/utils/modules.js +21 -34
  74. package/dist/node/utils/once.d.ts +10 -0
  75. package/dist/node/utils/once.js +20 -0
  76. package/dist/node/utils/packages.d.ts +1 -0
  77. package/dist/node/utils/packages.js +1 -1
  78. package/dist/node/utils/project-config.d.ts +3 -0
  79. package/dist/node/utils/project-config.js +8 -0
  80. package/dist/node/utils/serialized-task-queue.d.ts +9 -0
  81. package/dist/node/utils/serialized-task-queue.js +17 -0
  82. package/dist/node/utils/transform.d.ts +11 -0
  83. package/dist/node/utils/transform.js +58 -0
  84. package/dist/node/vite-plugin.d.ts +1 -1
  85. package/dist/node/vite-plugin.js +11 -27
  86. package/dist/options.d.ts +3 -4
  87. package/dist/runtime/{taro → client/taro}/api.d.ts +0 -1
  88. package/dist/runtime/client/taro/api.js +9 -0
  89. package/dist/runtime/client/taro/component.d.ts +1 -0
  90. package/dist/runtime/client/taro/component.js +1 -0
  91. package/dist/runtime/client/taro/define-native-component.d.ts +7 -0
  92. package/dist/runtime/client/taro/define-native-component.js +4 -0
  93. package/dist/runtime/h5/app.d.ts +2 -0
  94. package/dist/runtime/h5/app.js +15 -0
  95. package/dist/runtime/h5/taro-runtime.d.ts +1 -1
  96. package/dist/runtime/h5/taro-runtime.js +1 -4
  97. package/dist/runtime/wx/amphibious/bootstrap.d.ts +4 -0
  98. package/dist/runtime/wx/amphibious/bootstrap.js +16 -0
  99. package/dist/runtime/wx/amphibious/transport.d.ts +2 -0
  100. package/dist/runtime/wx/amphibious/transport.js +4 -0
  101. package/dist/runtime/wx/capsule/app.d.ts +2 -0
  102. package/dist/runtime/wx/capsule/app.js +7 -0
  103. package/dist/runtime/wx/capsule/component.d.ts +3 -0
  104. package/dist/runtime/wx/capsule/component.js +4 -0
  105. package/dist/runtime/wx/capsule/page.d.ts +3 -0
  106. package/dist/runtime/wx/capsule/page.js +68 -0
  107. package/dist/runtime/wx/capsule/taro-runtime.d.ts +6 -0
  108. package/dist/runtime/wx/capsule/taro-runtime.js +6 -0
  109. package/dist/runtime/wx/dev/dev-runtime.d.ts +1 -0
  110. package/dist/runtime/wx/dev/dev-runtime.js +246 -0
  111. package/dist/runtime/wx/native/app.d.ts +1 -0
  112. package/dist/runtime/wx/native/app.js +3 -0
  113. package/dist/runtime/wx/native/component.d.ts +1 -0
  114. package/dist/runtime/wx/native/component.js +3 -0
  115. package/dist/runtime/wx/native/page.d.ts +1 -0
  116. package/dist/runtime/wx/native/page.js +4 -0
  117. package/dist/runtime/wx/systemjs/system-core.d.ts +4 -0
  118. package/dist/runtime/wx/systemjs/system-core.js +331 -0
  119. package/package.json +21 -14
  120. package/src/node/plugins/client/client-taro.ts +23 -0
  121. package/src/node/plugins/client/constant.ts +5 -0
  122. package/src/node/plugins/{conditional-directives.ts → conditional/conditional-directives.ts} +33 -13
  123. package/src/node/plugins/css/plugins.ts +96 -0
  124. package/src/node/plugins/h5/constant.ts +4 -0
  125. package/src/node/plugins/h5/plugins.ts +197 -0
  126. package/src/node/plugins/h5/resolver/module-resolver.ts +32 -0
  127. package/src/node/plugins/h5/transform-app.ts +90 -0
  128. package/src/node/plugins/wx/dev/dev-host.ts +448 -0
  129. package/src/node/plugins/wx/dev/hmr-files.ts +55 -0
  130. package/src/node/plugins/wx/dev/patch-publisher.ts +49 -0
  131. package/src/node/plugins/wx/dev/plugin.ts +82 -0
  132. package/src/node/plugins/wx/dev/react-refresh.ts +227 -0
  133. package/src/node/plugins/wx/module.ts +97 -0
  134. package/src/node/plugins/wx/native/compile-native-component-interface.ts +47 -0
  135. package/src/node/plugins/wx/native/create-native-component-output.ts +57 -0
  136. package/src/node/plugins/wx/native/native-component-assets.ts +114 -0
  137. package/src/node/plugins/wx/native/native-component-interface.ts +265 -0
  138. package/src/node/plugins/wx/output/files.ts +27 -0
  139. package/src/node/plugins/wx/output/json.ts +79 -0
  140. package/src/node/plugins/wx/output/relative-root.ts +7 -0
  141. package/src/node/plugins/wx/output/templates.ts +141 -0
  142. package/src/node/plugins/wx/placement/placer.ts +172 -0
  143. package/src/node/plugins/wx/placement/plan.ts +306 -0
  144. package/src/node/plugins/wx/plugins.ts +165 -0
  145. package/src/node/plugins/wx/render/capsule-wrapper.ts +86 -0
  146. package/src/node/plugins/wx/render/capsule.ts +21 -0
  147. package/src/node/plugins/wx/render/native.ts +84 -0
  148. package/src/node/plugins/wx/render/transport.ts +157 -0
  149. package/src/node/plugins/wx/resolve/resolver.ts +125 -0
  150. package/src/node/plugins/wx/resolve/specialize-bootstrap.ts +27 -0
  151. package/src/node/plugins/wx/resolve/specialize-page-capsule.ts +29 -0
  152. package/src/node/utils/constant.ts +1 -0
  153. package/src/node/utils/memoize.ts +149 -0
  154. package/src/node/utils/modules.ts +36 -38
  155. package/src/node/utils/once.ts +21 -0
  156. package/src/node/utils/packages.ts +1 -1
  157. package/src/node/utils/project-config.ts +10 -0
  158. package/src/node/utils/serialized-task-queue.ts +20 -0
  159. package/src/node/utils/transform.ts +82 -0
  160. package/src/node/vite-plugin.ts +12 -32
  161. package/src/options.ts +3 -4
  162. package/src/runtime/client/taro/api.ts +11 -0
  163. package/src/runtime/client/taro/component.ts +1 -0
  164. package/src/runtime/client/taro/define-native-component.ts +15 -0
  165. package/src/runtime/h5/app.ts +25 -0
  166. package/src/runtime/h5/taro-runtime.ts +1 -4
  167. package/src/runtime/wx/amphibious/bootstrap.ts +22 -0
  168. package/src/runtime/wx/amphibious/transport.ts +10 -0
  169. package/src/runtime/wx/capsule/app.ts +9 -0
  170. package/src/runtime/wx/capsule/component.ts +6 -0
  171. package/src/runtime/wx/capsule/page.ts +96 -0
  172. package/src/runtime/wx/capsule/taro-runtime.ts +14 -0
  173. package/src/runtime/wx/dev/dev-runtime.ts +317 -0
  174. package/src/runtime/wx/native/app.ts +4 -0
  175. package/src/runtime/wx/native/component.ts +4 -0
  176. package/src/runtime/wx/native/page.ts +6 -0
  177. package/src/runtime/wx/systemjs/LICENSE +10 -0
  178. package/src/runtime/wx/systemjs/system-core.js +370 -0
  179. package/src/runtime/wx/systemjs/system.d.ts +55 -0
  180. package/src/runtime/wx/wechat.d.ts +52 -0
  181. package/README.zh.md +0 -521
  182. package/dist/node/build-context.d.ts +0 -25
  183. package/dist/node/build-context.js +0 -47
  184. package/dist/node/css/css-pipeline.d.ts +0 -35
  185. package/dist/node/css/css-pipeline.js +0 -154
  186. package/dist/node/plugins/conditional-directives.d.ts +0 -3
  187. package/dist/node/plugins/taro-runtime.d.ts +0 -5
  188. package/dist/node/plugins/taro-runtime.js +0 -18
  189. package/dist/node/targets/h5/plugin.d.ts +0 -6
  190. package/dist/node/targets/h5/plugin.js +0 -117
  191. package/dist/node/targets/h5/virtual-modules.d.ts +0 -5
  192. package/dist/node/targets/h5/virtual-modules.js +0 -60
  193. package/dist/node/targets/wx/companion-assets.d.ts +0 -19
  194. package/dist/node/targets/wx/companion-assets.js +0 -129
  195. package/dist/node/targets/wx/dev-server/development-session.d.ts +0 -32
  196. package/dist/node/targets/wx/dev-server/development-session.js +0 -215
  197. package/dist/node/targets/wx/dev-server/full-build-scheduler.d.ts +0 -14
  198. package/dist/node/targets/wx/dev-server/full-build-scheduler.js +0 -60
  199. package/dist/node/targets/wx/dev-server/js-utils.d.ts +0 -5
  200. package/dist/node/targets/wx/dev-server/js-utils.js +0 -28
  201. package/dist/node/targets/wx/dev-server/output.d.ts +0 -19
  202. package/dist/node/targets/wx/dev-server/output.js +0 -44
  203. package/dist/node/targets/wx/dev-server/rolldown-runtime-source.d.ts +0 -8
  204. package/dist/node/targets/wx/dev-server/rolldown-runtime-source.js +0 -95
  205. package/dist/node/targets/wx/dev-server/update-server-state.d.ts +0 -65
  206. package/dist/node/targets/wx/dev-server/update-server-state.js +0 -116
  207. package/dist/node/targets/wx/dev-server/update-transport.d.ts +0 -28
  208. package/dist/node/targets/wx/dev-server/update-transport.js +0 -212
  209. package/dist/node/targets/wx/dev-server/vite-bundled-dev-adapter.d.ts +0 -44
  210. package/dist/node/targets/wx/dev-server/vite-bundled-dev-adapter.js +0 -145
  211. package/dist/node/targets/wx/development-files.d.ts +0 -8
  212. package/dist/node/targets/wx/development-files.js +0 -8
  213. package/dist/node/targets/wx/plugin.d.ts +0 -6
  214. package/dist/node/targets/wx/plugin.js +0 -144
  215. package/dist/node/targets/wx/react-refresh.d.ts +0 -4
  216. package/dist/node/targets/wx/react-refresh.js +0 -38
  217. package/dist/node/targets/wx/virtual-modules.d.ts +0 -16
  218. package/dist/node/targets/wx/virtual-modules.js +0 -120
  219. package/dist/node/utils/async.d.ts +0 -8
  220. package/dist/node/utils/async.js +0 -16
  221. package/dist/node/utils/filesystem.d.ts +0 -13
  222. package/dist/node/utils/filesystem.js +0 -43
  223. package/dist/runtime/taro/api.js +0 -11
  224. package/dist/runtime/taro/components.d.ts +0 -2
  225. package/dist/runtime/taro/components.js +0 -2
  226. package/dist/runtime/wx/page-update.d.ts +0 -6
  227. package/dist/runtime/wx/page-update.js +0 -157
  228. package/dist/runtime/wx/taro-runtime.d.ts +0 -5
  229. package/dist/runtime/wx/taro-runtime.js +0 -6
  230. package/dist/runtime/wx/update-client-state.d.ts +0 -68
  231. package/dist/runtime/wx/update-client-state.js +0 -84
  232. package/dist/runtime/wx/update-client.d.ts +0 -1
  233. package/dist/runtime/wx/update-client.js +0 -171
  234. package/src/node/build-context.ts +0 -62
  235. package/src/node/css/css-pipeline.ts +0 -171
  236. package/src/node/plugins/taro-runtime.ts +0 -22
  237. package/src/node/targets/h5/plugin.ts +0 -135
  238. package/src/node/targets/h5/virtual-modules.ts +0 -71
  239. package/src/node/targets/wx/companion-assets.ts +0 -174
  240. package/src/node/targets/wx/dev-server/development-session.ts +0 -271
  241. package/src/node/targets/wx/dev-server/full-build-scheduler.ts +0 -62
  242. package/src/node/targets/wx/dev-server/js-utils.ts +0 -33
  243. package/src/node/targets/wx/dev-server/output.ts +0 -56
  244. package/src/node/targets/wx/dev-server/rolldown-runtime-source.ts +0 -95
  245. package/src/node/targets/wx/dev-server/update-server-state.ts +0 -183
  246. package/src/node/targets/wx/dev-server/update-transport.ts +0 -261
  247. package/src/node/targets/wx/dev-server/vite-bundled-dev-adapter.ts +0 -203
  248. package/src/node/targets/wx/development-files.ts +0 -11
  249. package/src/node/targets/wx/plugin.ts +0 -164
  250. package/src/node/targets/wx/react-refresh.ts +0 -51
  251. package/src/node/targets/wx/virtual-modules.ts +0 -152
  252. package/src/node/utils/async.ts +0 -19
  253. package/src/node/utils/filesystem.ts +0 -45
  254. package/src/runtime/taro/api.ts +0 -13
  255. package/src/runtime/taro/components.ts +0 -2
  256. package/src/runtime/wx/page-update.ts +0 -230
  257. package/src/runtime/wx/react-refresh.d.ts +0 -20
  258. package/src/runtime/wx/taro-runtime.ts +0 -7
  259. package/src/runtime/wx/update-client-state.ts +0 -138
  260. package/src/runtime/wx/update-client.ts +0 -223
@@ -1,203 +0,0 @@
1
- import path from 'node:path'
2
- import type { ResolvedConfig, ViteDevServer } from 'vite'
3
- import { wxPagePreloadFile, wxUpdateControlFile, wxUpdateFile } from '../development-files.ts'
4
- import type { WxOutputFile } from './output.ts'
5
- import { wxRolldownRuntimeSource } from './rolldown-runtime-source.ts'
6
-
7
- const clientId = 'vite-plugin-taro-wx'
8
-
9
- /** HMR boundary shape returned by Vite's private WX DevEngine integration. */
10
- type WxDevEngineBoundary = {
11
- boundary: string
12
- acceptedVia: string
13
- }
14
-
15
- /** Update result shape returned by Vite's private bundled-development engine. */
16
- export type WxDevEngineUpdate =
17
- | { type: 'Noop' }
18
- | { type: 'FullReload'; reason?: string }
19
- | {
20
- type: 'Patch'
21
- code: string
22
- filename: string
23
- hmrBoundaries: WxDevEngineBoundary[]
24
- }
25
-
26
- type WxDevEngineInternal = {
27
- registerModules(clientId: string, modules: string[]): void
28
- ensureCurrentBuildFinish(): Promise<void>
29
- ensureLatestBuildOutput(): Promise<unknown>
30
- getBundleState(): Promise<{ lastBuildErrored: boolean }>
31
- triggerFullBuild(): void
32
- }
33
-
34
- type WxRolldownOptions = {
35
- output?: Record<string, unknown> | Array<Record<string, unknown>>
36
- experimental?: {
37
- devMode?: boolean | Record<string, unknown>
38
- [key: string]: unknown
39
- }
40
- [key: string]: unknown
41
- }
42
-
43
- type WxDevEngineClient = {
44
- send(payload: unknown): void
45
- }
46
-
47
- type ViteBundledDevInternal = {
48
- _devEngine?: WxDevEngineInternal
49
- clients: {
50
- setupIfNeeded(client: WxDevEngineClient, clientId: string): void
51
- }
52
- getRolldownOptions(): Promise<WxRolldownOptions>
53
- storeOutputFiles(output: WxOutputFile[]): void
54
- handleHmrOutput(client: WxDevEngineClient, files: string[], output: WxDevEngineUpdate, info?: unknown): void
55
- listen(): Promise<void>
56
- }
57
-
58
- type ViteBundledDevCallbacks = {
59
- onOutput(output: WxOutputFile[]): void
60
- onPatch(files: string[], output: WxDevEngineUpdate): boolean
61
- onError(message: string): void
62
- waitForInitialBundle(): Promise<void>
63
- }
64
-
65
- /** Isolates the private Vite bundled-development API used by the WX session. */
66
- export class ViteBundledDevAdapter {
67
- private bundledDev: ViteBundledDevInternal | undefined
68
-
69
- constructor(
70
- private readonly config: ResolvedConfig,
71
- private readonly server: ViteDevServer,
72
- private readonly callbacks: ViteBundledDevCallbacks
73
- ) {}
74
-
75
- install(): void {
76
- const bundledDev = this.server.environments.client.bundledDev as unknown as ViteBundledDevInternal | undefined
77
- if (!bundledDev) throw new Error('vite-plugin-taro requires Vite bundled development for WX development.')
78
- if (
79
- typeof bundledDev.getRolldownOptions !== 'function' ||
80
- typeof bundledDev.storeOutputFiles !== 'function' ||
81
- typeof bundledDev.handleHmrOutput !== 'function'
82
- ) {
83
- throw new Error('vite-plugin-taro does not support this Vite bundled-development API shape.')
84
- }
85
- this.bundledDev = bundledDev
86
- this.installOptions(bundledDev)
87
- this.installOutput(bundledDev)
88
- this.installPatches(bundledDev)
89
- this.installListener(bundledDev)
90
- }
91
-
92
- registerBundleModules(output: WxOutputFile[]): number {
93
- const moduleIds = new Set<string>()
94
- for (const item of output) {
95
- if (item.type !== 'chunk') continue
96
- for (const id of Object.keys(item.modules ?? {})) moduleIds.add(toStableModuleId(id, this.config.root))
97
- }
98
- this.registerModules([...moduleIds])
99
- return moduleIds.size
100
- }
101
-
102
- registerPatchModules(code: string): void {
103
- const moduleIds = new Set<string>()
104
- for (const match of code.matchAll(/create(?:Esm|Cjs)Initializer\("([^"]+)"/g)) moduleIds.add(match[1])
105
- this.registerModules([...moduleIds])
106
- }
107
-
108
- private registerModules(moduleIds: string[]): void {
109
- if (moduleIds.length) this.bundledDev?._devEngine?.registerModules(clientId, moduleIds)
110
- }
111
-
112
- async rebuild(): Promise<void> {
113
- const engine = this.bundledDev?._devEngine
114
- if (!engine) return
115
- engine.triggerFullBuild()
116
- await engine.ensureLatestBuildOutput()
117
- }
118
-
119
- private installOptions(bundledDev: ViteBundledDevInternal): void {
120
- const getRolldownOptions = bundledDev.getRolldownOptions.bind(bundledDev)
121
- bundledDev.getRolldownOptions = async () => {
122
- const options = await getRolldownOptions()
123
- if (!options.output) options.output = {}
124
- const output = getFirstOutput(options)
125
- const configuredOutput = this.config.build.rolldownOptions.output
126
- const desiredOutput = Array.isArray(configuredOutput) ? configuredOutput[0] : configuredOutput
127
- Object.assign(output, desiredOutput, {
128
- format: 'cjs',
129
- sourcemap: false,
130
- minify: false,
131
- banner: createWxDevelopmentBanner
132
- })
133
- options.experimental ??= {}
134
- options.experimental.devMode = {
135
- ...(typeof options.experimental.devMode === 'object' ? options.experimental.devMode : {}),
136
- lazy: false,
137
- // Rolldown compiles this source into runtime.js before any Taro/React module executes.
138
- implement: wxRolldownRuntimeSource
139
- }
140
- return options
141
- }
142
- }
143
-
144
- private installOutput(bundledDev: ViteBundledDevInternal): void {
145
- const storeOutputFiles = bundledDev.storeOutputFiles.bind(bundledDev)
146
- bundledDev.storeOutputFiles = (output) => {
147
- storeOutputFiles(output)
148
- this.callbacks.onOutput(output)
149
- }
150
- }
151
-
152
- private installPatches(bundledDev: ViteBundledDevInternal): void {
153
- const handleHmrOutput = bundledDev.handleHmrOutput.bind(bundledDev)
154
- bundledDev.handleHmrOutput = (client, files, output, info) => {
155
- if (output.type === 'Noop') return
156
- if (this.callbacks.onPatch(files, output)) handleHmrOutput(client, files, output, info)
157
- }
158
- }
159
-
160
- private installListener(bundledDev: ViteBundledDevInternal): void {
161
- const listen = bundledDev.listen.bind(bundledDev)
162
- bundledDev.listen = async () => {
163
- await listen()
164
- bundledDev.clients.setupIfNeeded({ send: (payload) => this.handlePayload(payload) }, clientId)
165
- const engine = bundledDev._devEngine
166
- if (!engine) throw new Error('vite-plugin-taro expected Vite to initialize the WX DevEngine.')
167
- await engine.ensureCurrentBuildFinish()
168
- if ((await engine.getBundleState()).lastBuildErrored) {
169
- throw new Error('The initial WX bundled-development build failed.')
170
- }
171
- await this.callbacks.waitForInitialBundle()
172
- }
173
- }
174
-
175
- private handlePayload(payload: unknown): void {
176
- if (typeof payload !== 'object' || payload === null) return
177
- const candidate = payload as { type?: unknown; err?: { message?: unknown } }
178
- if (candidate.type === 'error' && typeof candidate.err?.message === 'string') {
179
- this.callbacks.onError(candidate.err.message)
180
- }
181
- }
182
- }
183
-
184
- function toStableModuleId(id: string, root: string): string {
185
- const normalizedId = id.replace(/\\/g, '/')
186
- if (normalizedId.startsWith('\0') || !path.posix.isAbsolute(normalizedId)) return normalizedId
187
- return path.posix.relative(root.replace(/\\/g, '/'), normalizedId)
188
- }
189
-
190
- function getFirstOutput(options: WxRolldownOptions): Record<string, unknown> {
191
- if (!Array.isArray(options.output)) return options.output as Record<string, unknown>
192
- const output = options.output[0] ?? {}
193
- options.output[0] = output
194
- return output
195
- }
196
-
197
- /** Adds native direct dependencies whose execution order cannot be represented through the Rolldown graph. */
198
- function createWxDevelopmentBanner(chunk: { fileName: string }): string {
199
- if (chunk.fileName === 'app.js') return `require(${JSON.stringify(`./${wxUpdateControlFile}`)});`
200
- if (!chunk.fileName.startsWith('pages/') || !chunk.fileName.endsWith('.js')) return ''
201
- const prefix = '../'.repeat(chunk.fileName.split('/').length - 1)
202
- return `require(${JSON.stringify(`${prefix}runtime.js`)});require(${JSON.stringify(`${prefix}${wxPagePreloadFile}`)});require(${JSON.stringify(`${prefix}${wxUpdateFile}`)});`
203
- }
@@ -1,11 +0,0 @@
1
- /** Plugin-owned files added only to a WX development output. */
2
- export const wxDevelopmentDirectory = 'vpt-hmr'
3
-
4
- /** App-only metadata containing the local transport URL, token, and build ID. */
5
- export const wxUpdateControlFile = `${wxDevelopmentDirectory}/control.js`
6
-
7
- /** Stable page-component initialization required before replaying retained updates. */
8
- export const wxPagePreloadFile = `${wxDevelopmentDirectory}/preload.js`
9
-
10
- /** The one mutable, literal JavaScript update dependency required by every page. */
11
- export const wxUpdateFile = `${wxDevelopmentDirectory}/update.js`
@@ -1,164 +0,0 @@
1
- import path from 'node:path'
2
- import type { Plugin, PluginOption, UserConfig } from 'vite'
3
- import type { BuildContext } from '../../build-context.ts'
4
- import { normalizeModuleId, stripVirtualPrefix } from '../../utils/modules.ts'
5
- import { packageRequire } from '../../utils/packages.ts'
6
- import { emitWxCompanionAssets, type WxBundle } from './companion-assets.ts'
7
- import { WxDevelopmentSession } from './dev-server/development-session.ts'
8
- import { transformWxReactRefreshModule } from './react-refresh.ts'
9
- import { emitWxEntryChunks, isWxVirtualModuleId, loadWxVirtualModule, virtualWxAppId } from './virtual-modules.ts'
10
-
11
- const taroWxComponentsPath = packageRequire.resolve('@tarojs/plugin-platform-weapp/dist/components-react')
12
- const vitePluginTaroSourcePath = normalizeModuleId(path.dirname(packageRequire.resolve('vite-plugin-taro')))
13
- const taroVersion = String(packageRequire('@tarojs/runtime/package.json').version)
14
-
15
- /** Creates the plugins that own the complete WX build and development lifecycle. */
16
- export function createWxTargetPlugins(context: BuildContext): PluginOption[] {
17
- return [createWxTargetPlugin(context)]
18
- }
19
-
20
- function createWxTargetPlugin(context: BuildContext): Plugin {
21
- let developmentSession: WxDevelopmentSession | undefined
22
-
23
- return {
24
- name: 'vite-plugin-taro:wx',
25
-
26
- resolveId: {
27
- order: 'pre',
28
- handler(id) {
29
- return isWxVirtualModuleId(id) ? `\0${id}` : undefined
30
- }
31
- },
32
-
33
- load: {
34
- order: 'post',
35
- handler(id) {
36
- const cleanId = stripVirtualPrefix(id)
37
-
38
- emitWxEntryChunks(this, context, cleanId)
39
-
40
- return loadWxVirtualModule(cleanId, context)
41
- }
42
- },
43
-
44
- transform: {
45
- order: 'post',
46
- async handler(code, id) {
47
- if (!context.development) return
48
-
49
- const transformed = await transformWxReactRefreshModule(code, id, context.project.appComponentFile)
50
- return transformed === code ? undefined : transformed
51
- }
52
- },
53
-
54
- generateBundle: {
55
- order: 'post',
56
- async handler(_, bundle) {
57
- await emitWxCompanionAssets(this, bundle as WxBundle, context)
58
- }
59
- },
60
-
61
- configureServer: {
62
- order: 'post',
63
- handler(server) {
64
- developmentSession = new WxDevelopmentSession(context, server)
65
- developmentSession.install()
66
- }
67
- },
68
-
69
- closeBundle() {
70
- return developmentSession?.close()
71
- }
72
- }
73
- }
74
-
75
- /** Supplies the complete WX target configuration from the same target owner as its plugin. */
76
- export function createWxViteConfig(context: BuildContext): UserConfig {
77
- return {
78
- define: createWxTaroDefines(),
79
- experimental: context.development ? { bundledDev: true } : undefined,
80
- css: {
81
- lightningcss: {
82
- visitor: {
83
- // keep CSS3 style single colon :before, :after
84
- // while WeChat Mini Program does not support the double colons versions
85
- Selector(selector) {
86
- return selector.map((component) => {
87
- if (
88
- component.type === 'pseudo-element' &&
89
- (component.kind === 'before' || component.kind === 'after')
90
- ) {
91
- return {
92
- type: 'pseudo-element' as const,
93
- kind: 'custom' as const,
94
- name: component.kind
95
- }
96
- }
97
- return component
98
- })
99
- }
100
- }
101
- }
102
- },
103
- resolve: {
104
- alias: [{ find: /^@tarojs\/components$/, replacement: taroWxComponentsPath }]
105
- },
106
- build: {
107
- target: 'es2018',
108
- assetsInlineLimit: 1024,
109
- cssCodeSplit: false,
110
- // weapp-tailwindcss has no minifier setting; retain Vite's production CSS minification.
111
- cssMinify: context.development ? false : 'lightningcss',
112
- minify: !context.development,
113
- rolldownOptions: {
114
- input: { app: virtualWxAppId },
115
- experimental: {
116
- // remove vite virtual module \0 in comments, which causes WeChat DevTools failed to compile
117
- attachDebugInfo: 'none'
118
- },
119
- output: {
120
- format: 'cjs',
121
- entryFileNames: '[name].js',
122
- assetFileNames: 'assets/[name][extname]',
123
- chunkFileNames: ({ name }) => `${name === 'rolldown-runtime' ? 'runtime' : name}.js`,
124
- strictExecutionOrder: true,
125
- codeSplitting: {
126
- includeDependenciesRecursively: false,
127
- minSize: 0,
128
- groups: [
129
- { name: 'taro', test: isWxTaroChunkModule, priority: 100 },
130
- { name: 'vendors', test: isNodeModule, priority: 10 },
131
- { name: 'common', minShareCount: 2, minModuleSize: 1, priority: 1 }
132
- ]
133
- }
134
- }
135
- }
136
- }
137
- }
138
- }
139
-
140
- function createWxTaroDefines(): Record<string, string> {
141
- return {
142
- 'process.env.FRAMEWORK': JSON.stringify('react'),
143
- 'process.env.SUPPORT_TARO_POLYFILL': JSON.stringify('disabled'),
144
- 'process.env.TARO_ENV': JSON.stringify('weapp'),
145
- 'process.env.TARO_PLATFORM': JSON.stringify('mini'),
146
- 'process.env.TARO_VERSION': JSON.stringify(taroVersion),
147
- ENABLE_ADJACENT_HTML: 'false',
148
- ENABLE_CLONE_NODE: 'false',
149
- ENABLE_CONTAINS: 'false',
150
- ENABLE_INNER_HTML: 'false',
151
- ENABLE_MUTATION_OBSERVER: 'false',
152
- ENABLE_SIZE_APIS: 'false',
153
- ENABLE_TEMPLATE_CONTENT: 'false'
154
- }
155
- }
156
-
157
- function isWxTaroChunkModule(id: string): boolean {
158
- const normalizedId = normalizeModuleId(id)
159
- return normalizedId.includes('/node_modules/@tarojs/') || normalizedId.startsWith(`${vitePluginTaroSourcePath}/`)
160
- }
161
-
162
- function isNodeModule(id: string): boolean {
163
- return normalizeModuleId(id).includes('/node_modules/')
164
- }
@@ -1,51 +0,0 @@
1
- import { transformWithOxc } from 'vite'
2
- import { normalizeModuleId } from '../../utils/modules.ts'
3
-
4
- /** Rewrites Vite's browser-oriented Refresh output for the WX App Service global environment. */
5
- export async function transformWxReactRefreshModule(
6
- code: string,
7
- id: string,
8
- appComponentFile: string
9
- ): Promise<string> {
10
- const appFile = normalizeModuleId(appComponentFile)
11
- const instrumented = normalizeModuleId(id) === appFile ? await instrumentWxAppComponent(code, appFile) : code
12
- return instrumented
13
- .replaceAll('window.$Refresh', 'globalThis.$Refresh')
14
- .replaceAll('window.__registerBeforePerformReactRefresh', 'globalThis.__registerBeforePerformReactRefresh')
15
- .replaceAll('window.__getReactRefreshIgnoredExports', 'globalThis.__getReactRefreshIgnoredExports')
16
- .replace(
17
- 'export function register(type, id) {',
18
- 'export function register(type, id) {\n if (globalThis.__VITE_PLUGIN_TARO_WX_PAGE_UPDATE__?.blockRefreshRegistration) return'
19
- )
20
- .replace(
21
- '\n performReactRefresh()\n',
22
- '\n globalThis.__VITE_PLUGIN_TARO_WX_PAGE_UPDATE__?.afterRefresh?.(performReactRefresh())\n'
23
- )
24
- }
25
-
26
- /** Creates the virtual preamble that installs React Refresh before the generated WX App entry executes. */
27
- export function createWxReactRefreshPreambleSource(): string {
28
- return `import RefreshRuntime from '/@react-refresh'
29
- RefreshRuntime.injectIntoGlobalHook(globalThis)
30
- globalThis.$RefreshReg$ = () => {}
31
- globalThis.$RefreshSig$ = () => (type) => type
32
- `
33
- }
34
-
35
- /** Adds Refresh registration to JSX-free App modules that Vite's normal JSX transform would otherwise skip. */
36
- async function instrumentWxAppComponent(code: string, appFile: string): Promise<string> {
37
- const transformed = await transformWithOxc(code, appFile, {
38
- lang: 'js',
39
- sourcemap: false,
40
- jsx: { refresh: true }
41
- })
42
- return `import {
43
- createSignatureFunctionForTransform as __wxCreateRefreshSignature,
44
- register as __wxRegisterRefreshType
45
- } from '/@react-refresh'
46
- const $RefreshReg$ = (type, id) => __wxRegisterRefreshType(type, ${JSON.stringify(`${appFile} `)} + id)
47
- const $RefreshSig$ = __wxCreateRefreshSignature
48
- ${transformed.code}
49
- if (import.meta.hot) import.meta.hot.accept()
50
- `
51
- }
@@ -1,152 +0,0 @@
1
- /**
2
- * Defines the generated WX application graph.
3
- *
4
- * App, page, and component IDs become native entry chunks. The Refresh preamble is an App bootstrap module, while the
5
- * page-preload ID deliberately becomes its own development file with a later, page-only execution phase.
6
- */
7
- import type { VitePluginTaroPageOption } from '../../../options.ts'
8
- import type { BuildContext } from '../../build-context.ts'
9
- import { createPageComponentImportPath, toViteFileImportPath } from '../../utils/modules.ts'
10
- import { resolvePackageFile } from '../../utils/packages.ts'
11
- import { wxPagePreloadFile } from './development-files.ts'
12
- import { createWxReactRefreshPreambleSource } from './react-refresh.ts'
13
-
14
- const wxTaroRuntimeImportPath = runtimeImportPath('taro-runtime.js')
15
- const wxPageUpdateImportPath = runtimeImportPath('page-update.js')
16
- const wxUpdateClientImportPath = runtimeImportPath('update-client.js')
17
-
18
- /** Generated native App entry. */
19
- export const virtualWxAppId = 'virtual:vite-plugin-taro/wx/app'
20
-
21
- /** Generated recursive Taro component entry. */
22
- const virtualWxComponentId = 'virtual:vite-plugin-taro/wx/component'
23
-
24
- /** Prefix for one generated native entry per configured page route. */
25
- const virtualWxPageIdPrefix = 'virtual:vite-plugin-taro/wx/page/'
26
-
27
- /** App bootstrap module that installs React Refresh globals before application modules execute. */
28
- const virtualWxRefreshPreambleId = 'virtual:vite-plugin-taro/wx/refresh-preamble'
29
-
30
- /** Development-only entry that initializes all configured page components before update replay. */
31
- const virtualWxPagePreloadId = 'virtual:vite-plugin-taro/wx/page-preload'
32
-
33
- type WxChunkEmitter = {
34
- emitFile(chunk: { type: 'chunk'; id: string; fileName: string; implicitlyLoadedAfterOneOf: string[] }): string
35
- }
36
-
37
- export function isWxVirtualModuleId(id: string): boolean {
38
- return (
39
- id === virtualWxAppId ||
40
- id === virtualWxComponentId ||
41
- id === virtualWxRefreshPreambleId ||
42
- id === virtualWxPagePreloadId ||
43
- id.startsWith(virtualWxPageIdPrefix)
44
- )
45
- }
46
-
47
- export function loadWxVirtualModule(id: string, context: BuildContext): string | undefined {
48
- if (id === virtualWxRefreshPreambleId) {
49
- return createWxReactRefreshPreambleSource()
50
- }
51
- if (id === virtualWxAppId) {
52
- return createWxAppEntrySource(context)
53
- }
54
- if (id === virtualWxComponentId) {
55
- return createWxComponentEntrySource()
56
- }
57
- if (id === virtualWxPagePreloadId) {
58
- return createWxPagePreloadSource(context)
59
- }
60
-
61
- if (id.startsWith(virtualWxPageIdPrefix)) {
62
- const pagePath = id.slice(virtualWxPageIdPrefix.length)
63
-
64
- const page = context.project.pages.find((candidate) => candidate.path === pagePath)
65
- if (page) {
66
- return createWxPageEntrySource(page, context)
67
- }
68
- }
69
- }
70
-
71
- /** Registers every configured page and the shared recursive component as eager WX entry chunks. */
72
- export function emitWxEntryChunks(emitter: WxChunkEmitter, context: BuildContext, id: string): void {
73
- if (id !== virtualWxAppId) return
74
-
75
- for (const page of context.project.pages) {
76
- emitter.emitFile({
77
- type: 'chunk',
78
- id: `${virtualWxPageIdPrefix}${page.path}`,
79
- fileName: `${page.path}.js`,
80
- implicitlyLoadedAfterOneOf: [id]
81
- })
82
- }
83
-
84
- emitter.emitFile({
85
- type: 'chunk',
86
- id: virtualWxComponentId,
87
- fileName: 'comp.js',
88
- implicitlyLoadedAfterOneOf: [id]
89
- })
90
-
91
- if (context.development) {
92
- emitter.emitFile({
93
- type: 'chunk',
94
- id: virtualWxPagePreloadId,
95
- fileName: wxPagePreloadFile,
96
- implicitlyLoadedAfterOneOf: [id]
97
- })
98
- }
99
- }
100
-
101
- function createWxAppEntrySource(context: BuildContext): string {
102
- const refreshPreamble = context.development ? `import ${JSON.stringify(virtualWxRefreshPreambleId)}\n` : ''
103
- const updateClient = context.development
104
- ? `import { startWxUpdateClient } from ${JSON.stringify(wxUpdateClientImportPath)}\n`
105
- : ''
106
- return `${refreshPreamble}${updateClient}import { createReactApp, ReactDOM } from ${JSON.stringify(wxTaroRuntimeImportPath)}
107
- import React from 'react'
108
- import AppComponent from ${JSON.stringify(toViteFileImportPath(context.project.appComponentFile))}
109
-
110
- const appConfig = ${JSON.stringify(context.project.appConfig)}
111
- App(createReactApp(AppComponent, React, ReactDOM, appConfig))
112
- ${context.development ? 'startWxUpdateClient()' : ''}
113
- `
114
- }
115
-
116
- function createWxPageEntrySource(page: VitePluginTaroPageOption, context: BuildContext): string {
117
- const hotUpdateImport = context.development
118
- ? `import { decorateWxPageConfig, registerWxPage } from ${JSON.stringify(wxPageUpdateImportPath)}\n`
119
- : ''
120
- const createConfig = `createPageConfig(PageComponent, '${page.path}', { root: { cn: [] } }, pageConfig)`
121
- const pageRegistration = context.development
122
- ? `registerWxPage(${JSON.stringify(page.path)}, () => Page(taroPageConfig))`
123
- : 'Page(taroPageConfig)'
124
- return `${hotUpdateImport}import { createPageConfig } from ${JSON.stringify(wxTaroRuntimeImportPath)}
125
- import PageComponent from ${JSON.stringify(createPageComponentImportPath(page.path))}
126
-
127
- const pageConfig = ${JSON.stringify(page.config)}
128
- const taroPageConfig = ${context.development ? `decorateWxPageConfig(${createConfig})` : createConfig}
129
- if (PageComponent && PageComponent.behaviors) {
130
- taroPageConfig.behaviors = (taroPageConfig.behaviors || []).concat(PageComponent.behaviors)
131
- }
132
- ${pageRegistration}
133
- `
134
- }
135
-
136
- function createWxPagePreloadSource(context: BuildContext): string {
137
- const imports = context.project.pages.map((page, index) => {
138
- return `import Page${index} from ${JSON.stringify(createPageComponentImportPath(page.path))}`
139
- })
140
- return `${imports.join('\n')}\nvoid [${context.project.pages.map((_, index) => `Page${index}`).join(', ')}]\n`
141
- }
142
-
143
- function runtimeImportPath(fileName: string): string {
144
- return toViteFileImportPath(resolvePackageFile('dist/runtime/wx', fileName))
145
- }
146
-
147
- function createWxComponentEntrySource(): string {
148
- return `import { createRecursiveComponentConfig } from ${JSON.stringify(wxTaroRuntimeImportPath)}
149
-
150
- Component(createRecursiveComponentConfig())
151
- `
152
- }
@@ -1,19 +0,0 @@
1
- /** Generic asynchronous coordination helpers for Node-side plugin services. */
2
- export class SerializedTaskQueue {
3
- private readonly reportError: (error: unknown) => void
4
- private tail = Promise.resolve()
5
-
6
- constructor(reportError: (error: unknown) => void) {
7
- this.reportError = reportError
8
- }
9
-
10
- enqueue(task: () => Promise<void>): Promise<void> {
11
- const work = this.tail.then(task)
12
- this.tail = work.catch(this.reportError)
13
- return work
14
- }
15
-
16
- async waitForIdle(): Promise<void> {
17
- await this.tail
18
- }
19
- }
@@ -1,45 +0,0 @@
1
- /** Node-only filesystem helpers shared by build targets and development services. */
2
- import fs from 'node:fs/promises'
3
- import path from 'node:path'
4
-
5
- type FileSource = string | Uint8Array
6
- type FileWrite = { file: string; source: FileSource }
7
-
8
- /** Writes through a sibling temporary file so observers never read partial contents. */
9
- export async function writeFileAtomically(file: string, source: FileSource): Promise<void> {
10
- await fs.mkdir(path.dirname(file), { recursive: true })
11
- const temporaryFile = `${file}.tmp`
12
- await fs.writeFile(temporaryFile, source)
13
- await fs.rename(temporaryFile, file)
14
- }
15
-
16
- export async function writeFilesAtomically(files: FileWrite[]): Promise<void> {
17
- await Promise.all(files.map(({ file, source }) => writeFileAtomically(file, source)))
18
- }
19
-
20
- /** Copies a directory when present and treats a missing optional source as empty. */
21
- export async function copyDirectoryIfExists(source: string, destination: string): Promise<void> {
22
- if (!source) return
23
- try {
24
- await fs.cp(source, destination, { recursive: true, force: true })
25
- } catch (error) {
26
- if (!isMissingFileError(error)) throw error
27
- }
28
- }
29
-
30
- /** Mirrors one optional file: copy existing files, ignore directories, and remove a missing source's destination. */
31
- export async function copyFileOrRemove(source: string, destination: string): Promise<void> {
32
- try {
33
- const stat = await fs.stat(source)
34
- if (stat.isDirectory()) return
35
- await fs.mkdir(path.dirname(destination), { recursive: true })
36
- await fs.copyFile(source, destination)
37
- } catch (error) {
38
- if (!isMissingFileError(error)) throw error
39
- await fs.rm(destination, { recursive: true, force: true })
40
- }
41
- }
42
-
43
- function isMissingFileError(error: unknown): error is NodeJS.ErrnoException {
44
- return error instanceof Error && 'code' in error && error.code === 'ENOENT'
45
- }
@@ -1,13 +0,0 @@
1
- /** Physical runtime module backing the public `virtual:taro/api` facade. */
2
- // Ensure Taro's React runtime registers its `initNativeApi` hook before @tarojs/taro is initialized.
3
- import '@tarojs/plugin-framework-react/dist/runtime'
4
- import { hooks } from '@tarojs/runtime'
5
- import Taro from '@tarojs/taro'
6
-
7
- if (hooks.isExist('initNativeApi')) {
8
- hooks.call('initNativeApi', Taro)
9
- }
10
-
11
- // @ts-expect-error @tarojs/taro declares export= types, but vite-plugin-taro target aliases expose runtime named exports.
12
- export * from '@tarojs/taro'
13
- export default Taro
@@ -1,2 +0,0 @@
1
- /** Physical runtime module backing the public `virtual:taro/components` facade. */
2
- export * from '@tarojs/components'