@tamagui/next-plugin 1.0.1-beta.21 → 1.0.1-beta.210

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.
@@ -0,0 +1,443 @@
1
+ import { existsSync } from 'fs'
2
+ import path, { dirname, join } from 'path'
3
+
4
+ import type { TamaguiOptions } from '@tamagui/static'
5
+ import browserslist from 'browserslist'
6
+ import CssMinimizerPlugin from 'css-minimizer-webpack-plugin'
7
+ import buildResolver from 'esm-resolve'
8
+ import InlineCSSPlugin from 'html-inline-css-webpack-plugin'
9
+ import MiniCSSExtractPlugin from 'mini-css-extract-plugin'
10
+ import { lazyPostCSS } from 'next/dist/build/webpack/config/blocks/css'
11
+ import { getGlobalCssLoader } from 'next/dist/build/webpack/config/blocks/css/loaders'
12
+ import { shouldExclude as shouldExcludeDefault } from 'tamagui-loader'
13
+ import webpack from 'webpack'
14
+
15
+ export type WithTamaguiProps = TamaguiOptions & {
16
+ useReactNativeWebLite: boolean
17
+ disableFontSupport?: boolean
18
+ aliasReactPackages?: boolean
19
+ includeCSSTest?: RegExp | ((path: string) => boolean)
20
+ inlineCSS?: boolean
21
+ shouldExtract?: (path: string, projectRoot: string) => boolean | undefined
22
+ shouldExcludeFromServer?: (props: {
23
+ context: string
24
+ request: string
25
+ fullPath: string
26
+ }) => boolean | string | undefined
27
+ }
28
+
29
+ export const withTamagui = (tamaguiOptions: WithTamaguiProps) => {
30
+ return (nextConfig: any = {}) => {
31
+ return {
32
+ ...nextConfig,
33
+ webpack: (webpackConfig: any, options: any) => {
34
+ const { dir, config, dev, isServer } = options
35
+
36
+ const resolver = buildResolver(join(dir, 'index.js'), {
37
+ constraints: 'node',
38
+ })
39
+
40
+ // @ts-ignore
41
+ if (typeof globalThis['__DEV__'] === 'undefined') {
42
+ // @ts-ignore
43
+ globalThis['__DEV__'] = dev
44
+ }
45
+
46
+ const isNext12 = typeof options.config?.swcMinify === 'boolean'
47
+ if (!isNext12) {
48
+ throw new Error(`Next.js 12 only supported`)
49
+ }
50
+
51
+ const prefix = `${isServer ? ' ssr ' : ' web '} |`
52
+
53
+ const safeResolves = (...resolves: [string, string][]) => {
54
+ const res: string[][] = []
55
+ for (const [out, mod] of resolves) {
56
+ if (out.endsWith('$')) {
57
+ res.push([out, mod])
58
+ continue
59
+ }
60
+ try {
61
+ res.push([out, resolveEsm(mod)])
62
+ } catch (err) {
63
+ if (out.includes(`@gorhom/bottom-sheet`)) {
64
+ continue
65
+ }
66
+ if (process.env.DEBUG?.startsWith('tamagui')) {
67
+ // eslint-disable-next-line no-console
68
+ console.log(prefix, `withTamagui skipping resolving ${out}`, err)
69
+ }
70
+ }
71
+ }
72
+ return Object.fromEntries(res)
73
+ }
74
+
75
+ const resolveEsm = (relativePath: string) => {
76
+ if (isServer) return require.resolve(relativePath)
77
+ const esm = resolver(relativePath)
78
+ return esm ? path.join(dir, esm) : require.resolve(relativePath)
79
+ }
80
+
81
+ const SEP = path.sep
82
+
83
+ // automatically compile our given components
84
+ const componentsFullPaths = safeResolves(
85
+ ...tamaguiOptions.components.map(
86
+ (moduleName) => [moduleName, moduleName] as [string, string]
87
+ )
88
+ )
89
+
90
+ const componentsBaseDirs = Object.entries(componentsFullPaths).map(
91
+ ([_moduleName, fullPath]) => {
92
+ let rootPath = dirname(fullPath as string)
93
+ while (rootPath.length > 1) {
94
+ const pkg = join(rootPath, 'package.json')
95
+ const hasPkg = existsSync(pkg)
96
+ if (hasPkg) {
97
+ return rootPath
98
+ } else {
99
+ rootPath = join(rootPath, '..')
100
+ }
101
+ }
102
+ throw new Error(`Couldn't find package.json in any path above: ${fullPath}`)
103
+ }
104
+ )
105
+
106
+ function isInComponentModule(fullPath: string) {
107
+ return componentsBaseDirs.some((componentDir) => fullPath.startsWith(componentDir))
108
+ }
109
+
110
+ // allows configuration
111
+ const shouldExclude = (path: string, projectRoot: string) => {
112
+ const res = tamaguiOptions.shouldExtract?.(path, projectRoot)
113
+ if (typeof res === 'boolean') {
114
+ return !res
115
+ }
116
+ if (isInComponentModule(path)) {
117
+ return false
118
+ }
119
+ return shouldExcludeDefault(path, projectRoot)
120
+ }
121
+
122
+ const rnw = tamaguiOptions.useReactNativeWebLite
123
+ ? 'react-native-web-lite'
124
+ : 'react-native-web'
125
+
126
+ const tamaguiAliases = safeResolves(
127
+ ['@tamagui/core/reset.css', '@tamagui/core/reset.css'],
128
+ ['@tamagui/core', '@tamagui/core'],
129
+ ['react-native-svg', '@tamagui/react-native-svg'],
130
+ // fixes https://github.com/kentcdodds/mdx-bundler/issues/143
131
+ ['react/jsx-runtime.js', 'react/jsx-runtime'],
132
+ ['react/jsx-runtime', 'react/jsx-runtime'],
133
+ ['react/jsx-dev-runtime.js', 'react/jsx-dev-runtime'],
134
+ ['react/jsx-dev-runtime', 'react/jsx-dev-runtime'],
135
+ ['react-native-reanimated', 'react-native-reanimated'],
136
+ ['react-native$', rnw],
137
+ ['react-native-web$', rnw],
138
+ ['@testing-library/react-native', '@tamagui/proxy-worm'],
139
+ ['@gorhom/bottom-sheet$', '@gorhom/bottom-sheet'],
140
+ // fix reanimated 3
141
+ ['react-native/Libraries/Renderer/shims/ReactFabric', '@tamagui/proxy-worm'],
142
+ ...(tamaguiOptions.aliasReactPackages
143
+ ? ([
144
+ ['react', 'react'],
145
+ ['react-dom', 'react-dom'],
146
+ ] as any)
147
+ : [])
148
+ )
149
+
150
+ const alias = {
151
+ ...(webpackConfig.resolve.alias || {}),
152
+ ...tamaguiAliases,
153
+ }
154
+
155
+ if (process.env.DEBUG) {
156
+ // eslint-disable-next-line no-console
157
+ console.log('Tamagui alias:', alias)
158
+ }
159
+
160
+ if (process.env.ANALYZE === 'true') {
161
+ Object.assign(webpackConfig.optimization, {
162
+ concatenateModules: false,
163
+ })
164
+ }
165
+
166
+ webpackConfig.resolve.alias = alias
167
+
168
+ webpackConfig.plugins.push(
169
+ new webpack.DefinePlugin({
170
+ 'process.env.IS_STATIC': '""',
171
+ 'process.env.TAMAGUI_TARGET': '"web"',
172
+ __DEV__: JSON.stringify(dev),
173
+ })
174
+ )
175
+
176
+ const excludeExports = tamaguiOptions.excludeReactNativeWebExports
177
+ if (Array.isArray(excludeExports)) {
178
+ if (excludeExports.includes('PressResponder')) {
179
+ console.warn(
180
+ `⚠️ Warning: as of beta 118, PressReponder shouldn't be excluded in excludeReactNativeWebExports`
181
+ )
182
+ }
183
+ try {
184
+ const regexStr = `react-native-web(-lite)?/.*(${excludeExports.join('|')}).*js`
185
+ const regex = new RegExp(regexStr)
186
+ // console.log(prefix, 'exclude', regexStr)
187
+ webpackConfig.plugins.push(
188
+ new webpack.NormalModuleReplacementPlugin(regex, resolveEsm('@tamagui/proxy-worm'))
189
+ )
190
+ } catch (err) {
191
+ // eslint-disable-next-line no-console
192
+ console.warn(
193
+ `Invalid names provided to excludeReactNativeWebExports: ${excludeExports.join(', ')}`
194
+ )
195
+ }
196
+ }
197
+
198
+ if (process.env.IGNORE_TS_CONFIG_PATHS) {
199
+ if (process.env.DEBUG) {
200
+ // eslint-disable-next-line no-console
201
+ console.log(prefix, 'ignoring tsconfig paths')
202
+ }
203
+ if (webpackConfig.resolve.plugins[0]) {
204
+ delete webpackConfig.resolve.plugins[0].paths['@tamagui/*']
205
+ delete webpackConfig.resolve.plugins[0].paths['tamagui']
206
+ }
207
+ }
208
+
209
+ // TODO document and make configurable
210
+ // replaces minifier with css-minimizer-webpack-plugin which handles deduping atomic styles
211
+ if (!dev) {
212
+ const cssMin = webpackConfig.optimization.minimizer.find((x) =>
213
+ x.toString().includes('css-minimizer-plugin')
214
+ )
215
+ if (cssMin) {
216
+ webpackConfig.optimization.minimizer = webpackConfig.optimization.minimizer.slice(
217
+ cssMin.index,
218
+ 1
219
+ )
220
+ }
221
+ webpackConfig.optimization.minimizer.push(new CssMinimizerPlugin())
222
+ }
223
+
224
+ webpackConfig.resolve.extensions = [
225
+ ...new Set(['.web.tsx', '.web.ts', '.web.js', ...webpackConfig.resolve.extensions]),
226
+ ]
227
+
228
+ // look for compiled js with jsx intact as specified by module:jsx
229
+ webpackConfig.resolve.mainFields.unshift('module:jsx')
230
+
231
+ if (isServer) {
232
+ const externalize = (context: string, request: string) => {
233
+ const fullPath = request[0] === '.' ? path.join(context, request) : request
234
+
235
+ if (tamaguiOptions.shouldExcludeFromServer) {
236
+ const userRes = tamaguiOptions.shouldExcludeFromServer({
237
+ context,
238
+ request,
239
+ fullPath,
240
+ })
241
+ if (userRes !== undefined) {
242
+ return userRes
243
+ }
244
+ }
245
+
246
+ if (isInComponentModule(fullPath)) {
247
+ return false
248
+ }
249
+
250
+ if (fullPath.includes('react-native-web-lite')) {
251
+ // always inline react-native-web-lite due to errors where next.js resolved the path to esm
252
+ return false
253
+ }
254
+
255
+ // must inline react-native so we can alias to react-native-web
256
+ if (fullPath === 'react-native' || fullPath.startsWith(`react-native${SEP}`)) {
257
+ return false
258
+ }
259
+
260
+ if (
261
+ // feather icons uses react-native-svg which needs to be aliased
262
+ // fullPath.includes('/lucide-icons/') ||
263
+ fullPath.startsWith('react-native-web') ||
264
+ fullPath.includes(`node_modules${SEP}react-native-web`) ||
265
+ new RegExp(`^(react-dom|react)${SEP}$`).test(fullPath)
266
+ ) {
267
+ return `commonjs ${fullPath}`
268
+ }
269
+ if (
270
+ fullPath.startsWith('moti') ||
271
+ fullPath.startsWith('solito') ||
272
+ fullPath === 'tamagui' ||
273
+ fullPath.startsWith('@tamagui') ||
274
+ fullPath === 'react-native-safe-area-context' ||
275
+ fullPath === 'expo-linear-gradient' ||
276
+ fullPath.startsWith('@react-navigation') ||
277
+ fullPath.startsWith('@gorhom')
278
+ ) {
279
+ return
280
+ }
281
+ if (/^@?react-native-/.test(request)) {
282
+ return false
283
+ }
284
+ return true
285
+ }
286
+
287
+ // externalize react native things from bundle
288
+ webpackConfig.externals = [
289
+ ...webpackConfig.externals.map((external) => {
290
+ if (typeof external !== 'function') {
291
+ return external
292
+ }
293
+ // only runs on server
294
+ return (ctx, cb) => {
295
+ const isCb = typeof cb === 'function'
296
+ const res = externalize(ctx.context, ctx.request)
297
+ if (isCb) {
298
+ if (typeof res === 'string') {
299
+ return cb(null, res)
300
+ }
301
+ if (res) {
302
+ return external(ctx, cb)
303
+ }
304
+ return cb()
305
+ }
306
+ return !res
307
+ ? Promise.resolve(undefined)
308
+ : typeof res === 'string'
309
+ ? Promise.resolve(res)
310
+ : external(ctx)
311
+ }
312
+ }),
313
+ ]
314
+ }
315
+
316
+ const oneOfRule = webpackConfig.module.rules.find((x) => !!x.oneOf)
317
+
318
+ const cssLoader = getGlobalCssLoader(
319
+ // @ts-ignore
320
+ {
321
+ assetPrefix: options.config.assetPrefix || config.assetPrefix,
322
+ future: nextConfig.future,
323
+ experimental: nextConfig.experimental || {},
324
+ isClient: !isServer,
325
+ isServer,
326
+ isDevelopment: dev,
327
+ },
328
+ // @ts-ignore
329
+ () => lazyPostCSS(dir, getSupportedBrowsers(dir, dev)),
330
+ []
331
+ )
332
+
333
+ if (oneOfRule) {
334
+ if (!tamaguiOptions.disableFontSupport) {
335
+ // fonts support
336
+ oneOfRule.oneOf.unshift({
337
+ test: /\.(woff(2)?|eot|ttf|otf)(\?v=\d+\.\d+\.\d+)?$/,
338
+ use: [
339
+ {
340
+ loader: require.resolve('url-loader'),
341
+ options: {
342
+ limit: nextConfig.inlineFontLimit || 1024,
343
+ fallback: require.resolve('file-loader'),
344
+ publicPath: `${nextConfig.assetPrefix || ''}/_next/static/chunks/fonts/`,
345
+ outputPath: `${isServer ? '../' : ''}static/chunks/fonts/`,
346
+ name: '[name].[ext]',
347
+ },
348
+ },
349
+ ],
350
+ })
351
+ }
352
+
353
+ const cssTest =
354
+ tamaguiOptions.includeCSSTest ??
355
+ ((file) => {
356
+ return file.endsWith('.css')
357
+ })
358
+
359
+ if (!dev) {
360
+ const postCSSLoader = cssLoader[cssLoader.length - 1]
361
+ // replace nextjs picky style rules with simple minicssextract
362
+ oneOfRule.oneOf.unshift({
363
+ test: cssTest,
364
+ use: [MiniCSSExtractPlugin.loader, 'css-loader', postCSSLoader],
365
+ sideEffects: true,
366
+ })
367
+ webpackConfig.plugins.push(
368
+ new MiniCSSExtractPlugin({
369
+ filename: 'static/css/[contenthash].css',
370
+ ignoreOrder: true,
371
+ runtime: false,
372
+ })
373
+ )
374
+ if (tamaguiOptions.inlineCSS) {
375
+ webpackConfig.plugins.push(new InlineCSSPlugin())
376
+ }
377
+ } else {
378
+ oneOfRule.oneOf.unshift({
379
+ test: cssTest,
380
+ sideEffects: true,
381
+ use: cssLoader,
382
+ })
383
+ }
384
+ }
385
+
386
+ const firstOneOfRule = webpackConfig.module.rules.findIndex((x) => x && !!x.oneOf)
387
+ const oneOfJSRules: any[] = webpackConfig.module.rules[firstOneOfRule].oneOf
388
+ const afterSWCLoaderIndex =
389
+ oneOfJSRules.findIndex(
390
+ (x) => x && x.use && x.use.loader === 'next-swc-loader' && x.issuerLayer !== 'api'
391
+ ) + 1
392
+ const swcLoader = oneOfJSRules[afterSWCLoaderIndex]
393
+
394
+ // put an earlier loader where we just do tamagui stuff before regular swc
395
+ oneOfJSRules.splice(
396
+ afterSWCLoaderIndex,
397
+ 0,
398
+ {
399
+ test: /(bottom-sheet|react-native-reanimated).*\.[tj]sx?$/,
400
+ use: [
401
+ {
402
+ loader: 'babel-loader',
403
+ options: {
404
+ presets: ['@babel/preset-react'],
405
+ plugins: ['react-native-reanimated/plugin'],
406
+ },
407
+ },
408
+ ],
409
+ },
410
+ {
411
+ test: /\.(jsx?|tsx?)$/,
412
+ exclude: (path: string) => shouldExclude(path, options.dir),
413
+ use: [
414
+ ...[].concat(swcLoader.use),
415
+ {
416
+ loader: 'tamagui-loader',
417
+ options: tamaguiOptions,
418
+ },
419
+ ],
420
+ }
421
+ )
422
+
423
+ if (typeof nextConfig.webpack === 'function') {
424
+ return nextConfig.webpack(webpackConfig, options)
425
+ }
426
+
427
+ return webpackConfig
428
+ },
429
+ }
430
+ }
431
+ }
432
+
433
+ function getSupportedBrowsers(dir, isDevelopment) {
434
+ let browsers
435
+ try {
436
+ browsers = browserslist.loadConfig({
437
+ path: dir,
438
+ env: isDevelopment ? 'development' : 'production',
439
+ })
440
+ } catch {}
441
+
442
+ return browsers
443
+ }
@@ -1,7 +1,12 @@
1
1
  import type { TamaguiOptions } from '@tamagui/static';
2
2
  export declare type WithTamaguiProps = TamaguiOptions & {
3
+ useReactNativeWebLite: boolean;
4
+ disableFontSupport?: boolean;
3
5
  aliasReactPackages?: boolean;
4
- shouldIncludeModuleServer?: (props: {
6
+ includeCSSTest?: RegExp | ((path: string) => boolean);
7
+ inlineCSS?: boolean;
8
+ shouldExtract?: (path: string, projectRoot: string) => boolean | undefined;
9
+ shouldExcludeFromServer?: (props: {
5
10
  context: string;
6
11
  request: string;
7
12
  fullPath: string;
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"withTamagui.d.ts","sourceRoot":"","sources":["../src/withTamagui.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AASrD,oBAAY,gBAAgB,GAAG,cAAc,GAAG;IAC9C,yBAAyB,CAAC,EAAE,CAAC,KAAK,EAAE;QAClC,OAAO,EAAE,MAAM,CAAA;QACf,OAAO,EAAE,MAAM,CAAA;QACf,QAAQ,EAAE,MAAM,CAAA;KACjB,KAAK,OAAO,GAAG,MAAM,GAAG,SAAS,CAAA;CACnC,CAAA;AAED,eAAO,MAAM,WAAW,mBAAoB,gBAAgB,mBACtC,GAAG,QA6SxB,CAAA"}