So, let's say whenever you say import filename from filename, Metro will first start with looking at the file extension, which is basically, is there a file name which exists with, let's say, .Android.ts. If yes, resolve it. If not, then go back to, then go to ios.ts. If not, then go and see if native.ts exists. If it doesn't, then fall back to .ts. This is something that Metro does right now.
So, it allows you to implement things which are specific to Android or specific to iOS, which is a very basic requirement, and sometimes you need it. What if we steal this idea and steal this idea to make it work on web? Let's see how.
So, Webpack has this config, which says resolve extensions, right? This is an array which defines the priority order for the files to be resolved. Now, what we'll do over here is we want to tell Webpack that you are doing whatever you want to do, like TSS and everything. What we will do is we'll put .web.ts and .web.tsx. So, the priority order is basically the way you define the elements in the array. Now, Webpack works basically whenever you say now import filename from filename, it will basically go and say, okay, filename.web.ts, does it exist? If yes, resolve it. If it doesn't, then go and just pick filename.ts.
Now, after we do this, what we have to do is we want to rename our files so that, you know, our platforms or our bundlers are able to pick what the specific file for that particular platform. So, what we'll do is we'll say text.web.tsx and we'll say text.native.tsx, and then we'll have, of course, an index.tsx, which will just do export text from text. Now, let's see if things are working so far. I'll just switch to VS Code and we'll just say text. So, this is basically a text component that we are basically working on. So, you see, this is text.native, this is text.web, and then we have index. Now, let's see if things work. So, all right. Things are rendering as we wanted them. Let me also show the native part. So, things are working absolutely fine. But if you look at this, there's a tiny error, which says, cannot file module text or its declaration. Now, the thing is, we made our bundlers understand how to resolve these files, but TypeScript still doesn't know. Now, the way to come around or solve this error is what we can do is we can define declarations, and we can just say export text from text.web. And things should work. Sorry, my bad.
Comments