Onsen UI + React Setup for Dummies

I wanted to try coding with Onsen UI and React combo. However, the setup instructions given in the Onsen UI tutorial were a bit chinese to me. It took me a while to get my repo ready for the coding. Here is how I did it.

First we need to initialise npm and install Webpack. npm is used to install JS libraries and Webpack packs them and your app to single package.

Init npm and install Webpack:

npm init -y
npm install webpack webpack-cli babel-loader css-loader file-loader style-loader --save

In package.json:

  • Remove "main":"index.js"
  • Add "private":"true"

Install Onsen UI:

npm install onsenui react-onsenui --save

Install React:

npm install react react-dom --save

Install Babel:

npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save

To .babelrc:

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

To webpack.config.js:

const path = require('path');

module.exports = {
  entry: './src/index.js',
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        loader: 'file-loader?name=fonts/[name].[ext]'
      }
    ]
   },
   output: {
     filename: 'main.js',
     path: path.resolve(__dirname, 'dist')
  }
};

At this point you should put the Onsen UI Hello World files to their place.

To dist/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
</head>

<body>
  <div id="app"></div>

  <script src="main.js"></script>
</body>
</html>

To src/index.js:

var React = require('react');
var ReactDOM = require('react-dom');
var ons = require('onsenui');
var Ons = require('react-onsenui');

// Webpack CSS import
import 'onsenui/css/onsenui.css';
import 'onsenui/css/onsen-css-components.css';

class App extends React.Component {
  handleClick() {
    ons.notification.alert('Hello world!');
  }

  render() {
    return (
      <Ons.Page>
        <Ons.Button onClick={this.handleClick}>Tap me!</Ons.Button>
      </Ons.Page>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

Note that we have split the index.html in two parts. dist/index.html is HTML-only and all the code is located in src/index.js. Webpack will read the index.js and build a package containing the code and all required libraries to dist/main.js. This package is included by the dist/index.html.

Also the React.createClass used in the Onsen UI example has been replaced with the class App extends React.Component since the previous is obsolete.

All set? Build with webpack:

npx webpack --config webpack.config.js

Now open dist/index.html and profit!

Leave a Reply

Your email address will not be published. Required fields are marked *

eighty nine + = ninety eight