@tamagui/next-plugin 1.0.1-beta.18 → 1.0.1-beta.180

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