Using NPM Packages


 Make sure you have nodejs installed. If not installed, go through this tutorial for nodejs (https://www.viastudy.com/p/node-js.html) installation.
Once you have nodejs installed, create a folder reactproj/.
To start with project setup, run command npm init.
This is how the folder structure will look like:
reactproj\
package.json
Now we will install the packages that we need.
Here are the list of packages for reactjs:
npm install react --save-dev
npm install react-dom --save-dev
npm install react-scripts --save-dev
Open the command prompt and run above commands inside the folder reactproj/.
Create a folder src/ where all the js code will come in that folder. All the code for reactjs project will be available in the src/ folder. Create a file index.js and add import react and react-dom, as shown below.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, from Viastudy Tutorials!</h1>,
    document.getElementById('root')
);
We have returned the basic code for reactjs. We will explain the details of it in the next chapter. We want to display Hello, from Guru99 Tutorials and the same is given to the dom element with id "root".It is taken from the index.html file, which is the start file, as shown below.
Create a folder public/ and add index.html in that as shown below
index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>ReactJS Demo</title> 
  </head>
  <body>
    <div id = "root"></div>
   </body>
</html>
The package react-scripts will take care of compiling the code and starting the server to display the html file i.e index.html. You need to add the command in package.json that will take care of using react-scripts to compile the code and start server as shown below:
 "scripts": {
    "start": "react-scripts start" 
  }
After installing all the packages and adding the above command, the final package.json is as follows:
Package.json
{
  "name": "reactproj",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "react-scripts start"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-scripts": "^3.1.1"
  }
}
To start testing reactjs run the command
npm run start
C:\reactproj>npm run start
> reactproj@1.0.0 start C:\reactproj
> react-scripts start
It will open browser with url http://localhost:3000/ as shown below:
public/index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>ReactJS Demo</title> 
  </head>
  <body>
    <div id = "root"></div>
  </body>
</html>

No comments:

Post a Comment