How to integrate react-native web to an existing react native project
We have a react-native project implemented using typescript
, react-navigation
, react-native-gesture-handler
, redux/toolkit
as the main packages
recently we integrated react-native-web into our project, but it is not running correctly.
there are several problems with our project:
-
we cannot load custom modules when we import them. for example:
import MyCustomComponent from './components/MyCustomComponent' <View style={{flex: 1, backgroundColor: 'green'}}> <MyCustomComponent/> <--- does not show up, event when it contains a simple View component, we will see a blank screen </View>
but when I define
MyCustomComponent
inside the current file, it shows up with no problem:function MyCustomComponent() { return( <View style={{flex:1, backgroundColor: 'yellow'}}></View> ) } export default function MyMainComponent() { return ( <View style={{flex:1, backgroundColor: 'green'}}> <MyCustomComponent/> <---- this shows up </View> ) }
-
anything that goes inside the redux
Provider
will not show up any more.
I think our webpack
configuration is wrong, but since I'm not expert in web development, I need some help to figure out what's wrong. here is our webpack configuration:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const appDirectory = path.resolve(__dirname);
const {presets} = require(`${appDirectory}/../babel.config.js`);
const compileNodeModules = [
// Add every react-native package that needs compiling
'react-native-gesture-handler',
'react-redux',
'react-native-reanimated',
'react-native-confirmation-code-field',
'react-native-calendars',
'@react-native-google-signin/google-signin',
'react-native-compressor',
'react-native-swipe-gestures',
'@react-native-async-storage',
'react-native-shared-element',
'@react-navigation',
'react-native-material-menu',
'@reduxjs/toolkit',
'react-navigation-shared-element',
'react-native-collapsible-tab-view',
'react-native-image-crop-picker',
'@react-native-community',
'react-nativbe-safe-area-context/lib',
'react-native-screens',
].map(moduleName =>
path.resolve(appDirectory, `../node_modules/${moduleName}`),
);
const babelLoaderConfiguration = {
test: /\.js$|tsx?$/,
// Add every directory that needs to be compiled by Babel during the build.
include: [
path.resolve(__dirname, '../index.web.js'), // Entry to your application
path.resolve(__dirname, '../src/index.web.tsx'), // Change this to your main App file
path.resolve(__dirname, '../src'),
...compileNodeModules,
],
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets,
plugins: ['react-native-web'],
},
},
};
const svgLoaderConfiguration = {
test: /\.svg$/,
use: [
{
loader: '@svgr/webpack',
},
],
};
const tsLoaderConfiguration = {
test: /\.(ts|tsx|web.ts|web.tsx)?$/,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true,
},
},
],
};
const imageLoaderConfiguration = {
test: /\.(gif|jpe?g|png)$/,
use: {
loader: 'url-loader',
options: {
name: '[name].[ext]',
esModule: false,
},
},
};
module.exports = {
entry: {
app: path.join(__dirname, '../index.web.js'),
},
output: {
path: path.resolve(appDirectory, 'dist'),
publicPath: '/',
filename: 'arcelor.bundle.js',
},
resolve: {
extensions: ['.web.tsx', '.web.ts', '.tsx', '.ts', '.web.js', '.js'],
alias: {
'react-native$': 'react-native-web',
},
},
module: {
rules: [
babelLoaderConfiguration,
imageLoaderConfiguration,
svgLoaderConfiguration,
tsLoaderConfiguration,
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, './index.html'),
filename: 'index.html',
inject: 'body',
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
// See: https://github.com/necolas/react-native-web/issues/349
// __DEV__: JSON.stringify(true),
__DEV__: process.env.NODE_ENV !== 'production',
process: {env: {}},
}),
],
};
I'm using webpack@^5.65.0
could anyone help me figure out what is the problem and how can I make react-native-web
work with our project? thanks
Solution 1:
getting Webpack up and running from scratch is not an easy task. I suggest you start with a ready to use an approach like cra or expo. then work your way up to customization.
Create-React-App
- firstly, install the dependencies:
yarn add react-native-web react-scripts react-dom
- create an HTML file in
public/index.html
and put the following content inside: gh:facebook/create-react-app/cra-template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<title>Your App Title</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
-
rename the
index.js
in project root toindex.native.js
. see -
create a js file in
src/index.js
and put the following content inside:
import { AppRegistry } from "react-native";
import { App } from "./App";
AppRegistry.registerComponent(appName, () => App);
AppRegistry.runApplication("App", {
rootTag: document.getElementById("root"),
});
- run the app by running
react-scripts start
Customization
you may need to integrate preprocessors like react-native-reanimated/plugin
to your babel config or edit your WebPack to add global variables like process.env
. In order to do that you can either use react-scripts eject
to have access to said configs or use tools like customize-cra.
Expo (Recommened)
In my opinion Expo is the best way to do it. Expo basically is create-react-app
but for react-native
that supports the react-native-web
.
You can set up the expo for the web for your project by following the official guide.
- install dependencies:
yarn add --global expo-cli
expo install react-native-web react-dom
yarn add expo
- modify your root
index.js
to something like this:
import { registerRootComponent } from 'expo';
import App from './App';
registerRootComponent(App);
- at this point you are ready to go. just rust
expo start:web
.
Customization
By running expo customize:web
, you have access to Babel and Webpack config files.
Typescript basePath
If you are using "baseUrl": "src"
in your tsconfig.json
. you may need to set up the Babel too. because it may not necessarily follow your tsconfig.
// babel.config.js
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
'react-native-reanimated/plugin',
[
'module-resolver',
{
root: ['src'],
extensions: ['.tsx', 'json', '.ts', '.js'],
},
],
],
};
};