Saturday, October 10, 2020

react sample project manually

 npm init -y


The above command will create a package.json file with default yes to all the project settings we need to type.


npm i -S react

npm i -S react-dom

the above will download the modules to node_modules subfolder and add entry to the "dependencies" section of package.json file created by init command above.


npm i -D webpack

The webpack is used for local development, a mini server kind of.It will generate a file bundle.js to generate the functionality.

same as -S but will add entries to "devDependencies".The difference is, these modules only for local development, they won't get installed on the server when deployed.


npm i -D babel-core

npm i -D babel-loader

npm i -D babel-preset-react

npm i -D babel-preset-es2015


The above modules are for converting es6 syntax of javascript to old syntax as many browsers doesn't support es6.

package.json file created.

{
  "name": "t",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.13.1",
    "react-dom": "^16.13.1"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.1.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "webpack": "^4.44.2"
  }
}


create files as below structure.

src\App.js

webpack.config.js

index.html


//webpack.config.js
webpack.js
------------
var webpack = require("webpack");
var path = require("path");

module.exports = {
 entry:{
  app: "./src/App.js"
  },
 output:{
   filename:"build/bundle.js",
     sourceMapFilename: "build/bundle.map"
  },
   devtool: '#source-map',
  
 module: {
    loaders: [
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/,
      loader: 'babel-loader',
      query:{
        presets:['react','es2015']   
     }
   ]
  }
  
}

App.js
//shortcut rcom<tab>

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class App extends Component{
  render(){
    return(
    <div>
      Cool react App
   </div>
   );
  }
}

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

Now, before creating index.html we need to convert the es6 to old javascript.

project folder# sudo npm install -g webpack
webpack -w 

This will create a build folder with bundle.js and other files.
Then add below code to index.html at the end of body tag inside it.

index.html

<body>
  <div id='root'></div>
  <script type="text/javascript" src="build/bundle.js"></script>
</body>

No comments:

Post a Comment