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,135 +0,0 @@
1
- import type { types as BabelTypes, NodePath, PluginObj } from '@babel/core'
2
- import babel from '@rolldown/plugin-babel'
3
- import type { Plugin, PluginOption, UserConfig } from 'vite'
4
- import type { BuildContext } from '../../build-context.ts'
5
- import { virtualTaroApiId } from '../../plugins/taro-runtime.ts'
6
- import { stripVirtualPrefix } from '../../utils/modules.ts'
7
- import { packageRequire } from '../../utils/packages.ts'
8
- import { createH5IndexHtmlTags, isH5VirtualModuleId, loadH5VirtualModule } from './virtual-modules.ts'
9
-
10
- /** Creates the plugins that own the complete H5 target lifecycle. */
11
- export function createH5TargetPlugins(context: BuildContext): PluginOption[] {
12
- return [...createH5SupportPlugins(), createH5TargetPlugin(context)]
13
- }
14
-
15
- function createH5TargetPlugin(context: BuildContext): Plugin {
16
- return {
17
- name: 'vite-plugin-taro:h5',
18
-
19
- resolveId: {
20
- order: 'pre',
21
- handler(id) {
22
- return isH5VirtualModuleId(id) ? `\0${id}` : undefined
23
- }
24
- },
25
-
26
- load: {
27
- order: 'post',
28
- handler(id) {
29
- return loadH5VirtualModule(stripVirtualPrefix(id), context)
30
- }
31
- },
32
-
33
- transformIndexHtml: {
34
- order: 'pre',
35
- handler() {
36
- return createH5IndexHtmlTags(context)
37
- }
38
- }
39
- }
40
- }
41
-
42
- /** Creates H5-only Babel transforms for Stencil CSS ordering and Taro API imports. */
43
- function createH5SupportPlugins(): PluginOption[] {
44
- return [
45
- babel({
46
- include: /[\\/]@stencil[\\/]core[\\/]internal[\\/]client[\\/]index\.js(?:\?.*)?$/,
47
- exclude: [],
48
- plugins: [rewriteStencilStyleInsertion]
49
- }),
50
- babel({
51
- plugins: [
52
- [
53
- packageRequire.resolve('babel-plugin-transform-taroapi'),
54
- {
55
- packageName: virtualTaroApiId,
56
- definition: packageRequire(
57
- packageRequire.resolve('@tarojs/plugin-platform-h5/dist/definition.json')
58
- )
59
- }
60
- ]
61
- ]
62
- })
63
- ]
64
- }
65
-
66
- /** Keeps Stencil-injected Taro component styles before application stylesheets. */
67
- function rewriteStencilStyleInsertion(): PluginObj {
68
- return {
69
- name: 'rewrite-stencil-style-insertion',
70
- visitor: {
71
- CallExpression(path: NodePath<BabelTypes.CallExpression>) {
72
- if (!isStencilStyleInsertBeforeCall(path)) return
73
- path.get('arguments.1').replaceWithSourceString(
74
- `scopeId.startsWith('sc-taro-') ? styleContainerNode.querySelector('style,link[rel="stylesheet"]') : styleContainerNode.querySelector('link')`
75
- )
76
- }
77
- }
78
- }
79
- }
80
-
81
- function isStencilStyleInsertBeforeCall(path: NodePath<BabelTypes.CallExpression>): boolean {
82
- return (
83
- path.get('callee').matchesPattern('styleContainerNode.insertBefore') &&
84
- path.get('arguments.0').toString() === 'styleElm' &&
85
- path.get('arguments.1').toString() === "styleContainerNode.querySelector('link')"
86
- )
87
- }
88
-
89
- /** Supplies the complete H5 target configuration from the same target owner as its plugins. */
90
- export function createH5ViteConfig(context: BuildContext): UserConfig {
91
- return {
92
- define: createH5TaroDefines(),
93
- resolve: {
94
- mainFields: ['main:h5', 'browser', 'module', 'jsnext:main', 'jsnext'],
95
- alias: [
96
- {
97
- find: /^@stencil\/core\/internal\/client$/,
98
- replacement: packageRequire.resolve('@stencil/core/internal/client', {
99
- paths: [packageRequire.resolve('@tarojs/components/package.json')]
100
- })
101
- },
102
- {
103
- find: /^@tarojs\/components$/,
104
- replacement: packageRequire.resolve('@tarojs/components/lib/react')
105
- },
106
- {
107
- find: /^@tarojs\/components\/dist\/components$/,
108
- replacement: packageRequire.resolve('@tarojs/components/dist/components')
109
- },
110
- {
111
- find: /^@tarojs\/taro$/,
112
- replacement: packageRequire.resolve('@tarojs/plugin-platform-h5/dist/runtime/apis')
113
- }
114
- ]
115
- },
116
- optimizeDeps: {
117
- exclude: ['@stencil/core/internal/client']
118
- },
119
- build: {
120
- target: 'es2018',
121
- minify: !context.development
122
- }
123
- }
124
- }
125
-
126
- function createH5TaroDefines(): Record<string, string> {
127
- return {
128
- 'process.env.FRAMEWORK': JSON.stringify('react'),
129
- 'process.env.SUPPORT_TARO_POLYFILL': JSON.stringify('disabled'),
130
- 'process.env.TARO_ENV': JSON.stringify('h5'),
131
- 'process.env.TARO_PLATFORM': JSON.stringify('web'),
132
- 'process.env.SUPPORT_DINGTALK_NAVIGATE': JSON.stringify('disabled'),
133
- DEPRECATED_ADAPTER_COMPONENT: 'false'
134
- }
135
- }
@@ -1,71 +0,0 @@
1
- import type { HtmlTagDescriptor } from 'vite'
2
- import type { JsonObject, VitePluginTaroPageOption } from '../../../options.ts'
3
- import type { BuildContext } from '../../build-context.ts'
4
- import { createPageComponentImportPath, toViteFileImportPath } from '../../utils/modules.ts'
5
- import { resolvePackageFile } from '../../utils/packages.ts'
6
-
7
- const h5TaroRuntimeImportPath = toViteFileImportPath(resolvePackageFile('dist/runtime/h5/taro-runtime.js'))
8
-
9
- const virtualH5EntryId = 'virtual:vite-plugin-taro/h5'
10
-
11
- export function isH5VirtualModuleId(id: string): boolean {
12
- return id === virtualH5EntryId
13
- }
14
-
15
- export function loadH5VirtualModule(id: string, context: BuildContext): string | undefined {
16
- if (id === virtualH5EntryId) return createH5EntrySource(context)
17
- }
18
-
19
- export function createH5IndexHtmlTags(context: BuildContext): HtmlTagDescriptor[] | undefined {
20
- if (context.project.target !== 'h5') return
21
- return [
22
- {
23
- tag: 'script',
24
- attrs: { type: 'module' },
25
- children: `import '${virtualH5EntryId}'`,
26
- injectTo: 'body'
27
- }
28
- ]
29
- }
30
-
31
- function createH5EntrySource(context: BuildContext): string {
32
- const appConfig = JSON.stringify(createH5AppConfig(context.project.appConfig))
33
- const routes = createH5RoutesSource(context.project.pages)
34
- return `import {
35
- createHashHistory,
36
- createReactApp,
37
- createRouter,
38
- handleAppMount,
39
- window
40
- } from ${JSON.stringify(h5TaroRuntimeImportPath)}
41
- import React from 'react'
42
- import ReactDOM from 'react-dom/client'
43
- import AppComponent from ${JSON.stringify(toViteFileImportPath(context.project.appComponentFile))}
44
-
45
- const config = window.__taroAppConfig = ${appConfig}
46
- config.routes = ${routes}
47
- const app = createReactApp(AppComponent, React, ReactDOM, config)
48
- const history = createHashHistory({ window })
49
- handleAppMount(config, history)
50
- createRouter(history, app, config, React)
51
- `
52
- }
53
-
54
- function createH5AppConfig(sharedAppConfig: JsonObject): JsonObject {
55
- return { router: {}, ...sharedAppConfig }
56
- }
57
-
58
- function createH5RoutesSource(pages: readonly VitePluginTaroPageOption[]): string {
59
- const routes = pages.map((page) =>
60
- [
61
- 'Object.assign({',
62
- ` path: ${JSON.stringify(page.path)},`,
63
- ' load: async function(context, params) {',
64
- ` const page = await import(${JSON.stringify(createPageComponentImportPath(page.path))})`,
65
- ' return [page, context, params]',
66
- ' }',
67
- `}, ${JSON.stringify(page.config)})`
68
- ].join('\n')
69
- )
70
- return `[\n${routes.join(',\n')}\n]`
71
- }
@@ -1,174 +0,0 @@
1
- import path from 'node:path'
2
- import { recursiveMerge } from '@tarojs/helper'
3
- import { Weapp as WxPlatform } from '@tarojs/plugin-platform-weapp'
4
- import type { JsonObject } from '../../../options.ts'
5
- import type { BuildContext } from '../../build-context.ts'
6
- import { normalizeModuleId } from '../../utils/modules.ts'
7
- import { packageRequire } from '../../utils/packages.ts'
8
-
9
- type WxAssetSource = string | Uint8Array
10
-
11
- export type WxBundle = Record<
12
- string,
13
- {
14
- type: 'asset' | 'chunk'
15
- source?: WxAssetSource
16
- modules?: Record<string, { renderedExports?: string[] }>
17
- }
18
- >
19
-
20
- type WxAssetEmitter = {
21
- emitFile(asset: { type: 'asset'; fileName: string; source: WxAssetSource }): string
22
- warn(message: string): void
23
- }
24
-
25
- type WxTemplateComponentConfig = {
26
- includes: Set<string>
27
- exclude: Set<string>
28
- thirdPartyComponents: Map<string, Set<string>>
29
- includeAll: boolean
30
- }
31
-
32
- const taroWxComponentsPath = packageRequire.resolve('@tarojs/plugin-platform-weapp/dist/components-react')
33
- const templateBuilder = createWxTemplateBuilder()
34
-
35
- export async function emitWxCompanionAssets(
36
- emitter: WxAssetEmitter,
37
- bundle: WxBundle,
38
- context: BuildContext
39
- ): Promise<void> {
40
- for (const asset of await createWxCompanionAssets(bundle, context)) {
41
- if (!asset) continue
42
- if (asset.source === undefined) {
43
- emitter.warn(
44
- `[vite-plugin-taro] WX companion asset "${asset.fileName}" is missing its source and was not emitted.`
45
- )
46
- continue
47
- }
48
- emitter.emitFile({ type: 'asset', fileName: asset.fileName, source: asset.source })
49
- }
50
- }
51
-
52
- async function createWxCompanionAssets(
53
- bundle: WxBundle,
54
- context: BuildContext
55
- ): Promise<({ fileName: string; source: WxAssetSource } | undefined)[]> {
56
- const json = (value: JsonObject) => (context.development ? JSON.stringify(value, null, 2) : JSON.stringify(value))
57
-
58
- return [
59
- { fileName: 'app.json', source: json(context.project.appConfig) },
60
- { fileName: 'app.wxss', source: await context.css.transformWxss(collectWxBundleStyles(bundle)) },
61
- {
62
- fileName: 'base.wxml',
63
- source: templateBuilder.buildTemplate(collectWxTemplateComponentConfig(bundle))
64
- },
65
- { fileName: 'utils.wxs', source: templateBuilder.buildXScript() },
66
- { fileName: 'comp.wxml', source: templateBuilder.buildBaseComponentTemplate('.wxml') },
67
- { fileName: 'comp.json', source: json(createWxComponentConfig()) },
68
- { fileName: 'project.config.json', source: json(createWxProjectConfig(context)) },
69
- context.project.projectPrivateConfigJson
70
- ? { fileName: 'project.private.config.json', source: json(context.project.projectPrivateConfigJson) }
71
- : undefined,
72
- { fileName: 'sitemap.json', source: json(context.project.sitemapJson) },
73
- ...context.project.pages.flatMap((page) => [
74
- {
75
- fileName: `${page.path}.wxml`,
76
- source: templateBuilder.buildPageTemplate(relativeWxRootAsset(page.path, 'base.wxml'), {
77
- content: page.config,
78
- path: page.path
79
- })
80
- },
81
- {
82
- fileName: `${page.path}.json`,
83
- source: json({
84
- ...page.config,
85
- usingComponents: { comp: relativeWxRootAsset(page.path, 'comp') }
86
- })
87
- },
88
- { fileName: `${page.path}.wxss`, source: '' }
89
- ])
90
- ]
91
- }
92
-
93
- function createWxProjectConfig(context: BuildContext): JsonObject {
94
- const projectConfig = context.project.projectConfigJson
95
- const setting = isJsonObject(projectConfig.setting) ? projectConfig.setting : {}
96
- return {
97
- ...projectConfig,
98
- setting: { ...setting, compileHotReLoad: true }
99
- }
100
- }
101
-
102
- function isJsonObject(value: unknown): value is JsonObject {
103
- return typeof value === 'object' && value !== null && !Array.isArray(value)
104
- }
105
-
106
- function createWxTemplateBuilder() {
107
- const platform = new WxPlatform(
108
- { helper: { recursiveMerge }, modifyWebpackChain() {}, registerPlatform() {} },
109
- {},
110
- {}
111
- )
112
- platform.modifyTemplate({})
113
- return platform.template
114
- }
115
-
116
- function relativeWxRootAsset(pagePath: string, rootAsset: string): string {
117
- const relativePath = path.posix.relative(path.posix.dirname(pagePath), rootAsset)
118
- return relativePath.startsWith('.') ? relativePath : `./${relativePath}`
119
- }
120
-
121
- function collectWxTemplateComponentConfig(bundle: WxBundle): WxTemplateComponentConfig {
122
- const config: WxTemplateComponentConfig = {
123
- includes: new Set([
124
- 'view',
125
- 'catch-view',
126
- 'static-view',
127
- 'pure-view',
128
- 'click-view',
129
- 'scroll-view',
130
- 'image',
131
- 'static-image',
132
- 'text',
133
- 'static-text'
134
- ]),
135
- exclude: new Set(),
136
- thirdPartyComponents: new Map(),
137
- includeAll: false
138
- }
139
- const components = findBundleModule(bundle, taroWxComponentsPath)
140
- for (const name of components?.renderedExports ?? []) config.includes.add(toDashed(name))
141
- return config
142
- }
143
-
144
- function findBundleModule(bundle: WxBundle, resolvedId: string): { renderedExports?: string[] } | undefined {
145
- const normalizedResolvedId = normalizeModuleId(resolvedId)
146
- for (const item of Object.values(bundle)) {
147
- if (item.type !== 'chunk') continue
148
- const found = Object.entries(item.modules ?? {}).find(([id]) => normalizeModuleId(id) === normalizedResolvedId)
149
- if (found) return found[1]
150
- }
151
- }
152
-
153
- function toDashed(value: string): string {
154
- return value.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()
155
- }
156
-
157
- function createWxComponentConfig(): JsonObject {
158
- return {
159
- component: true,
160
- styleIsolation: 'apply-shared',
161
- usingComponents: { comp: './comp' }
162
- }
163
- }
164
-
165
- function collectWxBundleStyles(bundle: WxBundle): string {
166
- const styles: string[] = []
167
- for (const [fileName, item] of Object.entries(bundle)) {
168
- if (item.type !== 'asset' || !fileName.endsWith('.css')) continue
169
- const source = typeof item.source === 'string' ? item.source : new TextDecoder().decode(item.source)
170
- if (source) styles.push(source)
171
- delete bundle[fileName]
172
- }
173
- return styles.join('\n')
174
- }
@@ -1,271 +0,0 @@
1
- /**
2
- * Top-level owner of one WX development lifecycle.
3
- *
4
- * It serializes every output write, connects DevEngine patches to the update transport, and coalesces conservative full
5
- * rebuilds. No other module writes plugin-generated WX development files directly.
6
- */
7
- import fs from 'node:fs/promises'
8
- import path from 'node:path'
9
- import colors from 'picocolors'
10
- import type { ViteDevServer } from 'vite'
11
- import type { BuildContext } from '../../../build-context.ts'
12
- import { SerializedTaskQueue } from '../../../utils/async.ts'
13
- import {
14
- copyDirectoryIfExists,
15
- copyFileOrRemove,
16
- writeFileAtomically,
17
- writeFilesAtomically
18
- } from '../../../utils/filesystem.ts'
19
- import { wxDevelopmentDirectory, wxUpdateControlFile, wxUpdateFile } from '../development-files.ts'
20
- import { FullBuildScheduler } from './full-build-scheduler.ts'
21
- import { transformWxCompatibleJavaScript, transformWxOutputChunks } from './js-utils.ts'
22
- import { isWxFullBuildOutput, normalizeWxBundleStyles, setWxAppStyles, type WxOutputFile } from './output.ts'
23
- import { WxUpdateTransport } from './update-transport.ts'
24
- import { ViteBundledDevAdapter, type WxDevEngineUpdate } from './vite-bundled-dev-adapter.ts'
25
-
26
- const maxRetainedDeltaCount = 1_000
27
- const maxRetainedDeltaBytes = 16 * 1024 * 1024
28
- const fullBuildDebounceDelay = 100
29
-
30
- type WxDevServerContext = Pick<BuildContext, 'vite' | 'css'>
31
- type SessionSnapshot = Readonly<{
32
- lifecycle: 'open' | 'closed'
33
- outputPhase: 'starting' | 'ready'
34
- latestAppStyles: string
35
- }>
36
-
37
- /** Owns one WX bundled-development graph and all writes to its fixed output directory. */
38
- export class WxDevelopmentSession {
39
- private readonly adapter: ViteBundledDevAdapter
40
- private readonly updateTransport: WxUpdateTransport
41
- private readonly outDir: string
42
- private readonly initialBundle = Promise.withResolvers<void>()
43
- private readonly outputQueue: SerializedTaskQueue
44
- private readonly fullBuildScheduler: FullBuildScheduler
45
- private originalPrintUrls: (() => void) | undefined
46
- private snapshot: SessionSnapshot = { lifecycle: 'open', outputPhase: 'starting', latestAppStyles: '' }
47
-
48
- constructor(
49
- private readonly context: WxDevServerContext,
50
- private readonly server: ViteDevServer
51
- ) {
52
- const config = context.vite
53
- this.outDir = path.resolve(config.root, config.build.outDir)
54
- this.outputQueue = new SerializedTaskQueue((error) => this.reportOutputError(error))
55
- this.updateTransport = new WxUpdateTransport(
56
- server,
57
- () => this.requestFullBuild(),
58
- (buildId, source) =>
59
- this.outputQueue.enqueue(async () => {
60
- // A full build queued before this write invalidates the old batch instead of letting it overwrite
61
- // the new build's empty update.js.
62
- if (!this.updateTransport.isCurrentBuild(buildId)) return
63
- await writeFileAtomically(path.join(this.outDir, wxUpdateFile), source)
64
- })
65
- )
66
- this.adapter = new ViteBundledDevAdapter(config, server, {
67
- onOutput: (output) => this.handleBundleOutput(output),
68
- onPatch: (files, output) => this.handlePatch(files, output),
69
- onError: (message) => this.handleError(message),
70
- waitForInitialBundle: () => this.waitForInitialBundle()
71
- })
72
- this.fullBuildScheduler = new FullBuildScheduler(
73
- fullBuildDebounceDelay,
74
- () => this.adapter.rebuild(),
75
- (error) => this.reportRebuildError(error)
76
- )
77
- }
78
-
79
- private get config() {
80
- return this.context.vite
81
- }
82
-
83
- install(): void {
84
- this.updateTransport.install()
85
- this.server.httpServer?.once('listening', this.handleHttpListening)
86
- this.adapter.install()
87
- this.originalPrintUrls = this.server.printUrls.bind(this.server)
88
- this.server.printUrls = this.printUrls
89
- if (this.config.publicDir) this.server.watcher.add(this.config.publicDir)
90
- this.server.watcher.on('change', this.handleWatchedFile)
91
- this.server.watcher.on('add', this.handleWatchedFile)
92
- this.server.watcher.on('unlink', this.handleWatchedFile)
93
- }
94
-
95
- async close(): Promise<void> {
96
- if (this.snapshot.lifecycle === 'closed') return
97
- this.snapshot = { ...this.snapshot, lifecycle: 'closed' }
98
- this.server.watcher.off('change', this.handleWatchedFile)
99
- this.server.watcher.off('add', this.handleWatchedFile)
100
- this.server.watcher.off('unlink', this.handleWatchedFile)
101
- this.server.httpServer?.off('listening', this.handleHttpListening)
102
- if (this.server.printUrls === this.printUrls && this.originalPrintUrls) {
103
- this.server.printUrls = this.originalPrintUrls
104
- }
105
- this.updateTransport.close()
106
- await this.fullBuildScheduler.close()
107
- await this.outputQueue.waitForIdle()
108
- }
109
-
110
- private readonly printUrls = (): void => {
111
- this.originalPrintUrls?.()
112
- const projectDirectory = relativeToViteConfig(this.outDir, this.config.configFile, this.config.root)
113
- this.server.config.logger.info(
114
- ` ${colors.green('➜')} ${colors.bold('WeChat DevTools')}: ${colors.cyan(projectDirectory)}`
115
- )
116
- }
117
-
118
- private readonly handleHttpListening = (): void => {
119
- this.outputQueue.enqueue(() =>
120
- writeFileAtomically(path.join(this.outDir, wxUpdateControlFile), this.updateTransport.createControlSource())
121
- )
122
- }
123
-
124
- private readonly handleWatchedFile = (file: string): void => {
125
- if (isFileInside(file, this.config.publicDir)) {
126
- const destination = path.join(this.outDir, path.relative(this.config.publicDir, file))
127
- this.outputQueue.enqueue(() => copyFileOrRemove(file, destination))
128
- this.requestFullBuild()
129
- }
130
- }
131
-
132
- private handleBundleOutput(output: WxOutputFile[]): void {
133
- const appStyles = normalizeWxBundleStyles(output)
134
- const fullBuild = isWxFullBuildOutput(output)
135
-
136
- if (!fullBuild) {
137
- this.outputQueue.enqueue(async () => {
138
- await this.finalizeAppStyles(output, appStyles, false)
139
- await transformWxOutputChunks(output)
140
- await writeDevelopmentOutput(this.outDir, output)
141
- })
142
- return
143
- }
144
-
145
- const buildId = this.updateTransport.createBuildId()
146
- setDevelopmentAsset(output, wxUpdateControlFile, this.updateTransport.createControlSource(buildId))
147
- setDevelopmentAsset(output, wxUpdateFile, 'void 0;\n')
148
- this.outputQueue.enqueue(async () => {
149
- await this.finalizeAppStyles(output, appStyles, true)
150
- await transformWxOutputChunks(output)
151
- if (this.snapshot.outputPhase === 'starting') {
152
- // The directory is plugin-owned; clearing it once removes stale files from previous protocol designs.
153
- await fs.rm(path.join(this.outDir, wxDevelopmentDirectory), { recursive: true, force: true })
154
- }
155
- // Invalidate old HTTP reports before writing the new build epoch into the fixed DevTools directory.
156
- this.updateTransport.commitFullBuild(buildId)
157
- await writeDevelopmentOutput(this.outDir, output)
158
- await copyDirectoryIfExists(this.config.publicDir, this.outDir)
159
- await this.context.css.captureFullBuild()
160
- const moduleCount = this.adapter.registerBundleModules(output)
161
- this.snapshot = { ...this.snapshot, outputPhase: 'ready' }
162
- this.initialBundle.resolve()
163
- this.server.config.logger.info(
164
- `[vite-plugin-taro] WX bundle ready (${moduleCount} modules, ${output.length} files)`
165
- )
166
- })
167
- }
168
-
169
- private async finalizeAppStyles(
170
- output: WxOutputFile[],
171
- source: string | undefined,
172
- fullBuild: boolean
173
- ): Promise<void> {
174
- if (source !== undefined) {
175
- const transformed = await this.context.css.transformWxss(source)
176
- this.snapshot = { ...this.snapshot, latestAppStyles: transformed }
177
- setWxAppStyles(output, transformed)
178
- } else if (fullBuild && this.snapshot.latestAppStyles) {
179
- setWxAppStyles(output, this.snapshot.latestAppStyles)
180
- }
181
- }
182
-
183
- private handlePatch(files: string[], output: WxDevEngineUpdate): boolean {
184
- if (!isSafeJavaScriptPatch(files, output)) {
185
- this.requestFullBuild()
186
- return false
187
- }
188
-
189
- this.adapter.registerPatchModules(output.code)
190
- this.outputQueue.enqueue(async () => {
191
- const transformed = await this.context.css.transformNativePatch(output.code, output.filename, files)
192
- if ('requiresFullBuild' in transformed) {
193
- this.requestFullBuild()
194
- return
195
- }
196
- const compatibleCode = await transformWxCompatibleJavaScript(transformed.code, output.filename)
197
- if (
198
- this.updateTransport.retainedDeltaCount >= maxRetainedDeltaCount ||
199
- this.updateTransport.retainedDeltaBytes + Buffer.byteLength(compatibleCode) >= maxRetainedDeltaBytes
200
- ) {
201
- this.requestFullBuild()
202
- return
203
- }
204
- this.updateTransport.addDelta(compatibleCode)
205
- })
206
- return true
207
- }
208
-
209
- private handleError(message: string): void {
210
- this.server.config.logger.error('[vite-plugin-taro] WX update failed', { error: new Error(message) })
211
- }
212
-
213
- private requestFullBuild(): void {
214
- this.fullBuildScheduler.request()
215
- }
216
-
217
- private async waitForInitialBundle(): Promise<void> {
218
- await this.initialBundle.promise
219
- await this.outputQueue.waitForIdle()
220
- }
221
-
222
- private reportOutputError(error: unknown): void {
223
- const normalizedError = error instanceof Error ? error : new Error(String(error))
224
- this.server.config.logger.error(
225
- `[vite-plugin-taro] WX development output failed: ${normalizedError.stack ?? normalizedError.message}`
226
- )
227
- }
228
-
229
- private reportRebuildError(error: unknown): void {
230
- const normalizedError = error instanceof Error ? error : new Error(String(error))
231
- this.server.config.logger.error('[vite-plugin-taro] WX rebuild failed', { error: normalizedError })
232
- }
233
- }
234
-
235
- function writeDevelopmentOutput(outDir: string, output: WxOutputFile[]): Promise<void> {
236
- return writeFilesAtomically(
237
- output.map((item) => ({
238
- file: path.join(outDir, item.fileName),
239
- source: item.type === 'chunk' ? item.code : item.source
240
- }))
241
- )
242
- }
243
-
244
- function setDevelopmentAsset(output: WxOutputFile[], fileName: string, source: string): void {
245
- const index = output.findIndex((item) => item.type === 'asset' && item.fileName === fileName)
246
- const asset: WxOutputFile = { type: 'asset', fileName, source }
247
- if (index >= 0) output[index] = asset
248
- else output.push(asset)
249
- }
250
-
251
- function relativeToViteConfig(outDir: string, configFile: string | undefined, root: string): string {
252
- const configDirectory = configFile ? path.dirname(configFile) : root
253
- const relativePath = path.relative(configDirectory, outDir).replaceAll('\\', '/')
254
- if (!relativePath) return '.'
255
- return relativePath.startsWith('.') ? relativePath : `./${relativePath}`
256
- }
257
-
258
- function isFileInside(file: string, directory: string): boolean {
259
- if (!directory) return false
260
- const relative = path.relative(directory, file)
261
- return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative)
262
- }
263
-
264
- function isSafeJavaScriptPatch(
265
- files: string[],
266
- output: WxDevEngineUpdate
267
- ): output is Extract<WxDevEngineUpdate, { type: 'Patch' }> {
268
- if (output.type !== 'Patch' || output.hmrBoundaries.length === 0) return false
269
- if (output.code.includes('__vite__updateStyle') || output.code.includes('.updateStyle(')) return false
270
- return files.every((file) => /\.[cm]?[jt]sx?$/.test(file))
271
- }