Install dependencies
React dependencies
yarn add react react-dom yarn add -D @babel/core babel-loader @babel/preset-env @babel/preset-react yarn add -D webpack webpack-cli
Cordova webpack plugin
yarn add -D webpack@4 webpack-cli@3 webpack-dev-server@3 cordova plugin add cordova-plugin-webpack
Add config files
Add file “webpack.config.js”
var path = require('path') module.exports = { mode: 'development', entry: './react-src/index.js', output: { path: path.resolve(__dirname, 'www'), filename: 'index.bundle.js' }, devtool: 'inline-source-map', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] } }
Add .babelrc
{ "presets": ["@babel/preset-env", "@babel/preset-react"] }
Add a React component for testing
Add react-src/index.js
import React from 'react' import ReactDOM from 'react-dom' import App from './App' var app = { // Application Constructor initialize: function() { document.addEventListener('deviceready', this.onDeviceReady.bind(this), false); }, // deviceready Event Handler // // Bind any cordova events here. Common events are: // 'pause', 'resume', etc. onDeviceReady: function() { ReactDOM.render(<App />, document.getElementById('react-app')) }, }; app.initialize();
Add react-src/App.js
import React from 'react' const App = () => { return <div style={{ display: 'flex', justifyContent: 'center' }}>Hello from React</div> }
Embed bundle.js file into main html file at the end of <body> in main html file
<script type="text/javascript" src="index.bundle.js"></script>
Embed root tag for React component in main html file at position you want
<div id="react-app"></div>
Ignore bundle.js file in Git
www/index.bundle.js
Build Cordova app
cordova prepare cordova build -- --webpackConfig webpack.config.js
This add index.bundle.js into your www folder
Errors you can see
Error: Can’t resolve ‘react’
Remove ‘package-lock.json’ or ‘yarn.lock’ and run yarn again
React Error: Target Container is not a DOM Element
Check if you have root tag like this in html file or not
How to add react-native-web?
Install dependency
yarn add react react-dom react-native-web
Config resolve in “webpack.config.js”
module: { rules: [ ... ] }, resolve: { alias: { 'react-native$': 'react-native-web' } }
Leave a Reply