@tamagui/vite-plugin 1.59.2 → 1.59.4

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.
@@ -1,22 +1,21 @@
1
- import { readFile } from 'fs/promises'
2
1
  import { dirname } from 'path'
3
2
 
3
+ // import { esbuildCommonjs, viteCommonjs } from '@originjs/vite-plugin-commonjs'
4
4
  import { transform } from '@swc/core'
5
5
  import { parse } from 'es-module-lexer'
6
+ import { readFile } from 'fs-extra'
6
7
  import { OutputOptions } from 'rollup'
7
8
  import type { Plugin } from 'vite'
8
- import { viteExternalsPlugin } from 'vite-plugin-externals'
9
9
 
10
10
  import { extensions } from './extensions'
11
11
  import { getVitePath } from './getVitePath'
12
- import { prebuiltFiles } from './nativePrebuild'
13
12
 
14
13
  export function nativePlugin(options: { port: number; mode: 'build' | 'serve' }): Plugin {
15
14
  return {
16
15
  name: 'tamagui-native',
17
- enforce: 'post',
16
+ enforce: 'pre',
18
17
 
19
- config: (config) => {
18
+ config: async (config) => {
20
19
  config.define ||= {}
21
20
  config.define['process.env.REACT_NATIVE_SERVER_PUBLIC_PORT'] = JSON.stringify(
22
21
  `${options.port}`
@@ -44,6 +43,10 @@ export function nativePlugin(options: { port: number; mode: 'build' | 'serve' })
44
43
  config.optimizeDeps ??= {}
45
44
 
46
45
  config.optimizeDeps.disabled = true
46
+ // config.optimizeDeps.include = ['escape-string-regexp']
47
+
48
+ // config.plugins ||= []
49
+ // config.plugins.push(viteCommonjs())
47
50
 
48
51
  // config.optimizeDeps.needsInterop ??= []
49
52
  // config.optimizeDeps.needsInterop.push('react-native')
@@ -55,10 +58,15 @@ export function nativePlugin(options: { port: number; mode: 'build' | 'serve' })
55
58
 
56
59
  config.optimizeDeps.esbuildOptions.plugins ??= []
57
60
 
58
- config.optimizeDeps.esbuildOptions.alias = {
59
- 'react-native': '@tamagui/proxy-worm'
60
- }
61
-
61
+ // CANT DO THIS BECAUSE TAMAGUI PLUGIN DOES THIS! they clobber each other!
62
+ // config.optimizeDeps.esbuildOptions.plugins.push(
63
+ // esbuildCommonjs(['escape-string-regexp'])
64
+ // )
65
+
66
+ // config.optimizeDeps.esbuildOptions.alias = {
67
+ // 'react-native': '@tamagui/proxy-worm',
68
+ // }
69
+
62
70
  // config.optimizeDeps.esbuildOptions.plugins.push(
63
71
  // esbuildFlowPlugin(
64
72
  // /node_modules\/(react-native\/|@react-native\/)/,
@@ -97,103 +105,133 @@ export function nativePlugin(options: { port: number; mode: 'build' | 'serve' })
97
105
 
98
106
  config.build.rollupOptions.plugins ??= []
99
107
 
100
- if (options.mode === 'serve') {
101
- config.build.rollupOptions.external = [
102
- 'react-native',
103
- 'react',
104
- 'react/jsx-runtime',
105
- 'react/jsx-dev-runtime',
106
- ]
107
- }
108
+ // config.build.rollupOptions.external = [
109
+ // 'react-native',
110
+ // 'react',
111
+ // 'react/jsx-runtime',
112
+ // 'react/jsx-dev-runtime',
113
+ // ]
108
114
 
109
115
  if (!Array.isArray(config.build.rollupOptions.plugins)) {
110
116
  throw `x`
111
117
  }
112
118
 
113
119
  if (options.mode === 'build') {
114
- config.build.rollupOptions.plugins.push({
115
- name: `swap-react-native`,
120
+ config.plugins ||= []
121
+
122
+ // https://vitejs.dev/config/dep-optimization-options.html
123
+ // config.build.commonjsOptions ||= {}
124
+ // config.build.commonjsOptions.include = []
125
+
126
+ // CANT DO THIS BECAUSE TAMAGUI PLUGIN DOES THIS! they clobber each other!
127
+ // config.plugins.push(
128
+ // viteCommonjs({
129
+ // include: ['escape-string-regexp'],
130
+ // })
131
+ // )
132
+
133
+ // config.resolve.alias = {
134
+ // ...config.resolve.alias,
135
+ // 'react-native': virtualModuleId,
136
+ // }
137
+
138
+ const jsxRuntime = {
139
+ alias: 'virtual:react-jsx',
140
+ contents: await readFile(
141
+ require.resolve('@tamagui/react-native-prebuilt/jsx-runtime'),
142
+ 'utf-8'
143
+ ),
144
+ } as const
145
+
146
+ const virtualModules = {
147
+ 'react-native': {
148
+ alias: 'virtual:react-native',
149
+ contents: await readFile(
150
+ require.resolve('@tamagui/react-native-prebuilt'),
151
+ 'utf-8'
152
+ ),
153
+ },
154
+ react: {
155
+ alias: 'virtual:react',
156
+ contents: await readFile(
157
+ require.resolve('@tamagui/react-native-prebuilt/react'),
158
+ 'utf-8'
159
+ ),
160
+ },
161
+ 'react/jsx-runtime': jsxRuntime,
162
+ 'react/jsx-dev-runtime': jsxRuntime,
163
+ } as const
116
164
 
117
- async load(id) {
118
- if (id.endsWith('/react-native/index.js')) {
119
- const bundled = await readFile(prebuiltFiles.reactNative, 'utf-8')
120
- const code = `
121
- const run = () => {
122
- ${bundled
123
- .replace(
124
- `module.exports = require_react_native();`,
125
- `return require_react_native();`
126
- )
127
- .replace(
128
- `var require_jsx_runtime = `,
129
- `var require_jsx_runtime = global['__JSX__'] = `
130
- )
131
- .replace(
132
- `var require_react = `,
133
- `var require_react = global['__React__'] = `
134
- )}
135
- }
136
- const RN = run()
137
- ${RNExportNames.map((n) => `export const ${n} = RN.${n}`).join('\n')}
138
- `
139
- return {
140
- code,
165
+ config.plugins.unshift({
166
+ name: `swap-react-native`,
167
+ enforce: 'pre',
168
+
169
+ resolveId(id) {
170
+ for (const targetId in virtualModules) {
171
+ if (id === targetId || id.includes(`node_modules/${targetId}/`)) {
172
+ const info = virtualModules[targetId]
173
+ console.log('resolving...', id, 'to', info.alias)
174
+ return info.alias
141
175
  }
142
176
  }
143
177
  },
144
- })
145
178
 
146
- config.build.rollupOptions.plugins.push(
147
- viteExternalsPlugin(
148
- {
149
- react: '____react____',
150
- 'react/jsx-runtime': '____jsx____',
151
- 'react/jsx-dev-runtime': '____jsx____',
152
- },
153
- {
154
- useWindow: false,
179
+ load(id) {
180
+ for (const targetId in virtualModules) {
181
+ const info = virtualModules[targetId as keyof typeof virtualModules]
182
+ if (id === info.alias) {
183
+ return info.contents
184
+ }
155
185
  }
156
- )
157
- )
186
+ },
187
+ })
158
188
 
159
189
  config.build.rollupOptions.plugins.push({
160
190
  name: `force-export-all`,
161
191
 
162
192
  async transform(code, id) {
163
- const [imports, exports] = parse(code)
164
-
165
- let forceExports = ''
166
-
167
- // note that es-module-lexer parses export * from as an import (twice) for some reason
168
- let counts = {}
169
- for (const imp of imports) {
170
- if (imp.n && imp.n[0] !== '.') {
171
- counts[imp.n] ||= 0
172
- counts[imp.n]++
173
- if (counts[imp.n] == 2) {
174
- // star export
175
- const path = await getVitePath(dirname(id), imp.n)
176
- forceExports += `Object.assign(exports, require("${path}"));`
193
+ // if (!id.includes('/node_modules/')) {
194
+ // return
195
+ // }
196
+
197
+ try {
198
+ const [imports, exports] = parse(code)
199
+
200
+ let forceExports = ''
201
+
202
+ // note that es-module-lexer parses export * from as an import (twice) for some reason
203
+ let counts = {}
204
+ for (const imp of imports) {
205
+ if (imp.n && imp.n[0] !== '.') {
206
+ counts[imp.n] ||= 0
207
+ counts[imp.n]++
208
+ if (counts[imp.n] == 2) {
209
+ // star export
210
+ const path = await getVitePath(dirname(id), imp.n)
211
+ forceExports += `Object.assign(exports, require("${path}"));`
212
+ }
177
213
  }
178
214
  }
179
- }
180
-
181
- forceExports += exports
182
- .map((e) => {
183
- if (e.n === 'default') {
184
- return ''
185
- }
186
- let out = ''
187
- if (e.ln !== e.n) {
188
- // forces the "as x" to be referenced so it gets exported
189
- out += `__ignore = typeof ${e.n} === 'undefined' ? 0 : 0;`
190
- }
191
- out += `globalThis.____forceExport = ${e.ln}`
192
- return out
193
- })
194
- .join(';')
195
215
 
196
- return code + '\n' + forceExports
216
+ forceExports += exports
217
+ .map((e) => {
218
+ if (e.n === 'default') {
219
+ return ''
220
+ }
221
+ let out = ''
222
+ if (e.ln !== e.n) {
223
+ // forces the "as x" to be referenced so it gets exported
224
+ out += `__ignore = typeof ${e.n} === 'undefined' ? 0 : 0;`
225
+ }
226
+ out += `globalThis.____forceExport = ${e.ln}`
227
+ return out
228
+ })
229
+ .join(';')
230
+
231
+ return code + '\n' + forceExports
232
+ } catch (err) {
233
+ console.warn(`Error forcing exports, probably ok`, id)
234
+ }
197
235
  },
198
236
  })
199
237
 
@@ -244,12 +282,13 @@ export function nativePlugin(options: { port: number; mode: 'build' | 'serve' })
244
282
  }
245
283
 
246
284
  if (process.env.DEBUG) {
285
+ // rome-ignore lint/suspicious/noConsoleLog: <explanation>
247
286
  console.log('config..', config)
248
287
  }
249
288
 
250
- config.build.commonjsOptions = {
251
- include: /node_modules\/react\//,
252
- }
289
+ // config.build.commonjsOptions = {
290
+ // include: /node_modules\/react\//,
291
+ // }
253
292
 
254
293
  const updateOutputOptions = (out: OutputOptions) => {
255
294
  out.preserveModules = true
@@ -275,88 +314,6 @@ export function nativePlugin(options: { port: number; mode: 'build' | 'serve' })
275
314
  }
276
315
  }
277
316
 
278
- const RNExportNames = [
279
- 'AccessibilityInfo',
280
- 'ActivityIndicator',
281
- 'Button',
282
- 'DrawerLayoutAndroid',
283
- 'FlatList',
284
- 'Image',
285
- 'ImageBackground',
286
- 'InputAccessoryView',
287
- 'KeyboardAvoidingView',
288
- 'Modal',
289
- 'Pressable',
290
- 'RefreshControl',
291
- 'SafeAreaView',
292
- 'ScrollView',
293
- 'SectionList',
294
- 'StatusBar',
295
- 'Switch',
296
- 'Text',
297
- 'TextInput',
298
- 'Touchable',
299
- 'TouchableHighlight',
300
- 'TouchableNativeFeedback',
301
- 'TouchableOpacity',
302
- 'TouchableWithoutFeedback',
303
- 'View',
304
- 'VirtualizedList',
305
- 'VirtualizedSectionList',
306
- 'ActionSheetIOS',
307
- 'Alert',
308
- 'Animated',
309
- 'Appearance',
310
- 'AppRegistry',
311
- 'AppState',
312
- 'BackHandler',
313
- 'DeviceInfo',
314
- 'DevSettings',
315
- 'Dimensions',
316
- 'Easing',
317
- 'findNodeHandle',
318
- 'I18nManager',
319
- 'InteractionManager',
320
- 'Keyboard',
321
- 'LayoutAnimation',
322
- 'Linking',
323
- 'LogBox',
324
- 'NativeDialogManagerAndroid',
325
- 'NativeEventEmitter',
326
- 'Networking',
327
- 'PanResponder',
328
- 'PermissionsAndroid',
329
- 'PixelRatio',
330
- // 'PushNotificationIOS',
331
- 'Settings',
332
- 'Share',
333
- 'StyleSheet',
334
- 'Systrace',
335
- 'ToastAndroid',
336
- 'TurboModuleRegistry',
337
- 'UIManager',
338
- 'unstable_batchedUpdates',
339
- 'useColorScheme',
340
- 'useWindowDimensions',
341
- 'UTFSequence',
342
- 'Vibration',
343
- 'YellowBox',
344
- 'DeviceEventEmitter',
345
- 'DynamicColorIOS',
346
- 'NativeAppEventEmitter',
347
- 'NativeModules',
348
- 'Platform',
349
- 'PlatformColor',
350
- 'processColor',
351
- 'requireNativeComponent',
352
- 'RootTagContext',
353
- // 'unstable_enableLogBox',
354
- // 'ColorPropType',
355
- // 'EdgeInsetsPropType',
356
- // 'PointPropType',
357
- // 'ViewPropTypes',
358
- ]
359
-
360
317
  // failed attempt to get vite to bundle rn, after a bunch of hacks still trouble
361
318
 
362
319
  // config.build.rollupOptions.plugins.push({
package/src/plugin.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { esbuildCommonjs } from '@originjs/vite-plugin-commonjs'
1
2
  import type { TamaguiOptions } from '@tamagui/static'
2
3
  import { watchTamaguiConfig } from '@tamagui/static'
3
4
  import type { Plugin } from 'vite'
@@ -40,7 +41,6 @@ export function tamaguiPlugin(
40
41
  ],
41
42
  define: {
42
43
  // reanimated support
43
- 'global.__x': {},
44
44
  _frameTimestamp: undefined,
45
45
  _WORKLET: false,
46
46
  __DEV__: `${env.mode === 'development' ? true : false}`,
@@ -62,20 +62,21 @@ export function tamaguiPlugin(
62
62
  },
63
63
  optimizeDeps: {
64
64
  // disabled: false,
65
- include:
66
- options.target !== 'native' ? ['styleq', 'react-native-reanimated'] : [],
65
+ include: options.target !== 'native' ? ['styleq'] : [],
67
66
  esbuildOptions: {
68
67
  jsx: 'transform',
69
- // plugins: [
70
- // esbuildCommonjs([
71
- // 'styleq',
72
- // 'inline-style-prefixer',
73
- // 'create-react-class',
74
- // 'copy-to-clipboard',
75
- // ]),
76
- // ],
68
+ plugins: [
69
+ esbuildCommonjs([
70
+ 'styleq',
71
+ 'inline-style-prefixer',
72
+ 'create-react-class',
73
+ 'copy-to-clipboard',
74
+ 'escape-string-regexp',
75
+ ]),
76
+ ],
77
77
  resolveExtensions: [
78
78
  '.web.js',
79
+ '.web.jsx',
79
80
  '.web.ts',
80
81
  '.web.tsx',
81
82
  '.js',
@@ -95,6 +96,7 @@ export function tamaguiPlugin(
95
96
  // mainFields: ['module:jsx', 'module', 'jsnext:main', 'jsnext', 'main'],
96
97
  extensions: [
97
98
  '.web.js',
99
+ '.web.jsx',
98
100
  '.web.ts',
99
101
  '.web.tsx',
100
102
  '.js',
@@ -1 +1 @@
1
- {"version":3,"file":"getVitePath.d.ts","sourceRoot":"","sources":["../src/getVitePath.ts"],"names":[],"mappings":"AAKA,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,QAAQ,UAAQ,mBAsBjB"}
1
+ {"version":3,"file":"getVitePath.d.ts","sourceRoot":"","sources":["../src/getVitePath.ts"],"names":[],"mappings":"AAKA,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,QAAQ,UAAQ,mBAoCjB"}
package/types/index.d.ts CHANGED
@@ -2,5 +2,4 @@ export * from './plugin';
2
2
  export * from './extract';
3
3
  export * from './nativePlugin';
4
4
  export * from './getVitePath';
5
- export * from './nativePrebuild';
6
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,gBAAgB,CAAA;AAC9B,cAAc,eAAe,CAAA;AAC7B,cAAc,kBAAkB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,gBAAgB,CAAA;AAC9B,cAAc,eAAe,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"nativePlugin.d.ts","sourceRoot":"","sources":["../src/nativePlugin.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAOlC,wBAAgB,YAAY,CAAC,OAAO,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAA;CAAE,GAAG,MAAM,CAsQvF"}
1
+ {"version":3,"file":"nativePlugin.d.ts","sourceRoot":"","sources":["../src/nativePlugin.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAKlC,wBAAgB,YAAY,CAAC,OAAO,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAA;CAAE,GAAG,MAAM,CA8SvF"}
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAErD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAElC;;GAEG;AAEH,wBAAgB,aAAa,CAC3B,OAAO,EAAE,cAAc,GAAG;IACxB,MAAM,CAAC,EAAE,KAAK,GAAG,QAAQ,CAAA;IACzB,qBAAqB,CAAC,EAAE,OAAO,CAAA;IAC/B,yBAAyB,CAAC,EAAE,OAAO,CAAA;CACpC,GACA,MAAM,CA+GR"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAErD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAElC;;GAEG;AAEH,wBAAgB,aAAa,CAC3B,OAAO,EAAE,cAAc,GAAG;IACxB,MAAM,CAAC,EAAE,KAAK,GAAG,QAAQ,CAAA;IACzB,qBAAqB,CAAC,EAAE,OAAO,CAAA;IAC/B,yBAAyB,CAAC,EAAE,OAAO,CAAA;CACpC,GACA,MAAM,CAgHR"}
@@ -1,137 +0,0 @@
1
- import { readFile } from 'fs/promises'
2
- import { join } from 'path'
3
-
4
- import * as babel from '@babel/core'
5
- import { build } from 'esbuild'
6
-
7
- import { extensions } from './extensions'
8
-
9
- async function nativeBabelFlowTransform(input: string) {
10
- return await new Promise<string>((res, rej) => {
11
- babel.transform(
12
- input,
13
- {
14
- presets: ['module:metro-react-native-babel-preset'],
15
- },
16
- (err: any, { code }) => {
17
- if (err) rej(err)
18
- res(code)
19
- }
20
- )
21
- })
22
- }
23
-
24
- const prebuiltDir = join(process.cwd(), 'testing-area')
25
- export const prebuiltFiles = {
26
- react: join(prebuiltDir, 'react.js'),
27
- reactJSXRuntime: join(prebuiltDir, 'react-jsx-runtime.js'),
28
- reactNative: join(prebuiltDir, 'react-native.js'),
29
- }
30
-
31
- export async function nativePrebuild() {
32
- // rome-ignore lint/suspicious/noConsoleLog: <explanation>
33
-
34
- // await build({
35
- // bundle: true,
36
- // entryPoints: [require.resolve('@tamagui/core')],
37
- // outfile: prebuiltFiles.reactNative,
38
- // format: 'cjs',
39
- // target: 'node20',
40
- // jsx: 'transform',
41
- // jsxFactory: 'react',
42
- // allowOverwrite: true,
43
- // platform: 'node',
44
- // external: ['react-native', 'react', 'react/jsx-runtime'],
45
- // loader: {
46
- // '.png': 'dataurl',
47
- // '.jpg': 'dataurl',
48
- // '.jpeg': 'dataurl',
49
- // '.gif': 'dataurl',
50
- // },
51
- // define: {
52
- // __DEV__: 'true',
53
- // 'process.env.NODE_ENV': `"development"`,
54
- // // TODO
55
- // 'process.env.REACT_NATIVE_SERVER_PUBLIC_PORT': JSON.stringify('8081'),
56
- // },
57
- // logLevel: 'warning',
58
- // resolveExtensions: extensions,
59
- // })
60
-
61
- if (process.env.SKIP_PREBUILD_RN) {
62
- return
63
- }
64
-
65
- console.log(`Prebuilding React Native (one time cost...)`)
66
-
67
- await Promise.all([
68
- build({
69
- bundle: true,
70
- entryPoints: [require.resolve('react-native')],
71
- outfile: prebuiltFiles.reactNative,
72
- format: 'cjs',
73
- target: 'node20',
74
- jsx: 'transform',
75
- jsxFactory: 'react',
76
- allowOverwrite: true,
77
- platform: 'node',
78
- loader: {
79
- '.png': 'dataurl',
80
- '.jpg': 'dataurl',
81
- '.jpeg': 'dataurl',
82
- '.gif': 'dataurl',
83
- },
84
- define: {
85
- __DEV__: 'true',
86
- 'process.env.NODE_ENV': `"development"`,
87
- // TODO
88
- 'process.env.REACT_NATIVE_SERVER_PUBLIC_PORT': JSON.stringify('8081'),
89
- },
90
- logLevel: 'warning',
91
- resolveExtensions: extensions,
92
- plugins: [
93
- {
94
- name: 'remove-flow',
95
- setup(build) {
96
- build.onResolve(
97
- {
98
- filter: /HMRClient/,
99
- },
100
- async (input) => {
101
- return {
102
- path: require.resolve('@tamagui/vite-native-hmr'),
103
- }
104
- }
105
- )
106
-
107
- build.onLoad(
108
- {
109
- filter: /.*.js/,
110
- },
111
- async (input) => {
112
- if (
113
- !input.path.includes('react-native') &&
114
- !input.path.includes(`vite-native-hmr`)
115
- ) {
116
- return
117
- }
118
-
119
- const code = await readFile(input.path, 'utf-8')
120
-
121
- // omg so ugly but no class support?
122
- const outagain = await nativeBabelFlowTransform(code)
123
-
124
- return {
125
- contents: outagain,
126
- loader: 'jsx',
127
- }
128
- }
129
- )
130
- },
131
- },
132
- ],
133
- }),
134
-
135
- ,
136
- ])
137
- }