I came across a great medium posts about creating a multiplatform (iOS/Android/Web) React Native project, which I highly recommend and can be found here. It's really great and should be added to the official react-native-web documentation, in my opinion!
However, there was one missing piece, and that was how to add the proper
web.js extension. Out of the box, React Native is configured to automatically import files based on the platform being used. For example, you could have a
Button.ios.js and a
Button.android.js, and when you do
import Button from './components/Button, React Native will be smart enough to pick the proper extension for the platform being built.
The medium article mentioned above doesn't cover properly adding the
web.js extension, but it's really quite easy after understanding what is actually happening.
In the article, it has you pull in the
react-scripts dependency, and then modify your package.json so you can do something like
yarn web or
npm run web and your web project will be built. What is actually happening is that
react-scripts is a package from the
create-react-app project. It does a lot of magic under the hood, but what it's doing for us in this case is pulling in webpack as a dependency so you can build your React Native Web project. React Native uses the metro bundler by default for ios and android projects.
So now that we know that webpack is being used under the hood, we can add a directory in the root of our project called
web (to match the existing
android folders) that will hold the web specific config files. Once that is done, simply create a new file in
web/webpack.config.js that contains the following
It's quite verbose, but in the end we are providing webpack a config file that adds
extensions: ['.web.js', '.js'], to provide support for the new
web.js extension. This webpack config was taken from the react-native-web documentation, and you can see that there's a
// ...the rest of your config section, so if you have any webpack specific changes you should add them there. I haven't done a ton of testing, but with a new project created using the medium article, this webpack config seems to work.
Now we should be good to go, you can use
file.js and it will apply to all platforms,
file.native.js to apply to both iOS and Android projects (but not web) or
file.web.js for only the web!