Linking React File

Importing "react.min.js" using a script tag will mean the "React" object is a global variable.
Importing "react-dom.min.js" using a script tag will mean the "ReactDOM" object is a global variable.
Notice that the script reference to "index.js" is at the bottom of the body.
The JavaScript code does not contain any JSX.


index.html

<!DOCTYPE html> 
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</head>

<body>
<div id="app"></div>
<script src="index.js" type="text/javascript"></script>
</body>
</html>

index.js

var App = React.createClass({ 
  displayName: 'App',
  render: function() {
    // The second parameter is an object of attributes for the element (if any)
    return React.createElement('div', { }, 'Hello World');
  }
});
 
ReactDOM.render(
  React.createElement(App),
  document.getElementById('app')
);

JSX - Linking File

If you want to put your JSX code into a separate file you need to install and use a local web server.
If you just include a script tag pointing to your JSX file you will receive a "cross origin requests" console error.
One way to get around this is to use [[Webpack]] which has its own web server.
When using a local web server the JSX code can easily be converted into regular Javascript.
This JSX conversion can be done using a Webpack module called [[Babel]]


Install node.js and npm

Before we can install Webpack we first need to install node.js and npm.
[[more information]]


Generate package.json file

Open File Explorer and browse to the (C:\temp\react) folder.
Create a new subfolder called "linking" (C:\temp\react\linking).
Open a command prompt (run as admin).
Change to that folder and initialise npm.

cd c:\temp\react\linking 
npm init

It will prompt you for the following information:

package name: (linking) - press Enter 
version: (1.0.0) - press Enter
description: - press Enter
entry point: (index.js) - press Enter
test command: - press Enter
git repository: - press Enter
keywords: - press Enter
author: - press Enter
license: (ISC) - press Enter
Is this ok? (yes) - press Enter

This will create a "package.json" file in the folder (C:\temp\react\linking).


Install Webpack

[[more information]]
This lets you bundle all your javascript files into a single file.

npm install --save-dev webpack 
npm install --save-dev webpack-cli
npm install --save-dev webpack-dev-server

This will create a new subfolder called "node_modules" (C:\temp\react\linking\node_modules).
The '--save-dev' switch will add these modules as a devDependency in the package.json file.


Install Babel

[[more information]]
This lets you compile JSX into regular Javascript.
This lets you transpile ES 2015 (ES6) Javascript into ES 2009 (ES5) Javascript code.

npm install --save-dev babel-loader 
npm install --save-dev @babel/core
npm install --save-dev @babel/preset-react

Install React

Instead of using the React CDN reference we can use the corresponding React webpack modules.
Install the react webpack module.
This lets you build user interfaces using React.

npm install --save-dev react 

Install the react dom webpack module.
This lets you work with the DOM from within React.

npm install --save-dev react-dom 

Install Type Definitions

Install the type definitions for React.

npm install --save-dev @types/react 

Edit package.json file

Open your browser and drag the "package.json" file onto a new tab to view the contents.
All the webpack modules that have been installed will appear as devDependencies.
Open NotePad++ and drag the "package.json" file onto it.
Delete the "main" parameter (under description) because this is not required.

{ 
  "name": "linking",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.23.2",
    "@babel/preset-react": "^7.22.15",
    "@types/react": "^18.2.28",
    "babel-loader": "^9.1.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  },
}

Create index.html file

Open File Explorer in the root folder (C:\temp\react\linking).
Create a new subfolder called "linking" (C:\temp\react\linking\public).
Create a NotePad file with the following contents and save it as 'index.html'.
This file contains html code that links to webpackbundle.js.

<!DOCTYPE html> 
<html>
<body>
   <h3>BetterSolutions.com</h3>
   <div id="app"></div>
   <script src="webpackbundle.js"></script>
</body>
</html>

Create index.jsx file

Open File Explorer in the root folder (C:\temp\react\linking).
Create a new subfolder called "linking" (C:\temp\react\linking\src).
Create a NotePad file with the following contents and save it as 'index.jsx'.
This file contains ES 2009 javascript and JSX code that uses React.

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

ReactDOM.render(
  <div>Hello React</div>,
  document.getElementById('app')
);

Create webpack.config.js

Open File Explorer in the root folder (C:\temp\react\linking).
Create a NotePad file with the following contents and save it as 'webpack.config.js'.
This file tells webpack the location and filename of our top level/entry javascript file ("index.jsx").
This file tells webpack to bundle all the javascript files into a single file called "webpackbundle.js".
This file tells webpack to use the babel-loader with the additional React preset.

module.exports = { 
  entry: __dirname + '/src/index.jsx',
  output: {
      filename: 'webpackbundle.js'
   },
  module: {
    rules: [
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        use : {
           loader: 'babel-loader',
           options: {
             presets: ['@babel/preset-react']
           }
        }
      }
    ]
  }
};

The "webpackbundle.js" file will be automatically generated and used on the local server.
This file is not saved or accessible anywhere in the root folder (C:\temp\react\linking).


Launch Browser

You are now in a position to launch webpack and start the local development server.
Open a command prompt (run as admin).
Change to the corresponding folder and execute the following 2 commands.

node ./node_modules/webpack/bin/webpack --mode development 
node ./node_modules/webpack-dev-server/bin/webpack-dev-server --mode development

Open your browser and display the URL - localhost:8080

Pressing "Ctrl + C" will stop the process from running in the command prompt.


Using Scripts

Add two extra script aliases (or shortcuts) to the package.json file to make it quicker to launch.
Open File Explorer in the root folder (C:\temp\react\linking)
Open your browser and display the URL - jsoneditoronline.org
Drag the package.json file onto the web page (left hand box) to view the contents.
Add two extra scripts one for "build" and one for "start".
Add the following two lines to the scripts property.

"scripts" : { 
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode development",
    "start": "webpack-dev-server --mode development"
},

In the packages.json file you do not need to specify the absolute paths.
Drag the packages.json file into NotePad so it can be edited.
Copy the new json from the web page (left hand box) and replace the text in the NotePad file, save and close.
The two node commands can now be replaced with these commands.

cd c:\temp\react\linking 
npm run build
npm run start

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext