11const { withNxMetro } = require ( '@nx/react-native' ) ;
22const { getDefaultConfig, mergeConfig } = require ( '@react-native/metro-config' ) ;
33const path = require ( 'path' ) ;
4+ const fs = require ( 'fs' ) ;
45
56const defaultConfig = getDefaultConfig ( __dirname ) ;
67
78const projectRoot = __dirname ;
89const monorepoRoot = path . resolve ( projectRoot , '../..' ) ;
910
11+ const getCustomResolver = ( defaultResolveRequest ) => ( context , moduleName , platform ) => {
12+ if ( platform === 'web' ) {
13+ if ( moduleName . includes ( 'NativeSourceCode' ) ||
14+ moduleName . includes ( 'NativePlatformConstants' ) ||
15+ moduleName . includes ( 'NativeDevSettings' ) ||
16+ moduleName . includes ( 'NativeLogBox' ) ||
17+ moduleName . includes ( 'NativeRedBox' )
18+ ) {
19+ return {
20+ type : 'empty' ,
21+ } ;
22+ } else if ( moduleName === 'react-native' ) {
23+ return {
24+ type : 'sourceFile' ,
25+ filePath : require . resolve ( 'react-native-web' ) ,
26+ } ;
27+ }
28+ }
29+
30+ // Everything else: default behavior
31+ return defaultResolveRequest ( context , moduleName , platform ) ;
32+ } ;
33+
1034/**
1135 * Metro configuration
1236 * https://reactnative.dev/docs/metro
@@ -18,6 +42,30 @@ const customConfig = {
1842 resolver : {
1943 unstable_enablePackageExports : true ,
2044 } ,
45+ server : {
46+ ...( defaultConfig . server || { } ) ,
47+ enhanceMiddleware : ( middleware ) => {
48+ return ( req , res , next ) => {
49+ if ( req . url === '/' || req . url === '/index.html' ) {
50+ const htmlPath = path . join ( projectRoot , 'index.html' ) ;
51+
52+ fs . readFile ( htmlPath , 'utf8' , ( err , data ) => {
53+ if ( err ) {
54+ res . writeHead ( 500 , { 'Content-Type' : 'text/plain' } ) ;
55+ res . end ( 'Error loading index.html: ' + err . message ) ;
56+ return ;
57+ }
58+
59+ res . writeHead ( 200 , { 'Content-Type' : 'text/html' } ) ;
60+ res . end ( data ) ;
61+ } ) ;
62+ return ;
63+ }
64+
65+ return middleware ( req , res , next ) ;
66+ } ;
67+ } ,
68+ } ,
2169} ;
2270
2371module . exports = withNxMetro ( mergeConfig ( defaultConfig , customConfig ) , {
@@ -26,4 +74,8 @@ module.exports = withNxMetro(mergeConfig(defaultConfig, customConfig), {
2674 path . resolve ( projectRoot , 'node_modules' ) ,
2775 path . resolve ( monorepoRoot , 'node_modules' ) ,
2876 ] ,
77+ } ) . then ( ( config ) => {
78+ // Nx overrides the resolveRequest, so we need to override it after the merge.
79+ config . resolver . resolveRequest = getCustomResolver ( config . resolver . resolveRequest ) ;
80+ return config ;
2981} ) ;
0 commit comments