npm create-react-appto initiate a react project any more because it is built by a bunch of CLI that we don't understand. Instead we can build a react object on our own by using webpack and babel (that transpiles ES6 Javascript into ES5, a version that is friendly to most browser).
The steps are essentially taken form a youtube tutorial:
Before going any further, our directory will look like:
We start off installing all necessary dependency:
npm i react react-dom npm i --save-dev webpack-dev-server webpack-cli npm install @babel/cli @babel/core @babel/node @babel/preset-env @babel/preset-react html-webpack-plugin -D npm install npm install -D babel-loaderFor html-webpack-plugin we need a template, let's save it in ./~src directory, which is written as
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>My React App</title> </head> <body> <div id="app"></div> </body> </html>Here
<div>
element with id "app" is a destination to which we build our react component. Next we configure our webpack and babel as follows: Create webpack.config.js and write
const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { entry: "./src/index.js", output: { path: path.join(__dirname, "/dist"), filename: "index_bundle.js" }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env", "@babel/preset-react"] } } } ] }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index.html" }) ] };Next in babel.config.js we write
module.exports = { presets: ["@babel/preset-env", "@babel/preset-react"] };Last 2 steps: First we write index.js to call the react library to render <App> component into <div id="app"/>
import React from "react"; import ReactDOM from "react-dom"; import App from "./components/App"; ReactDOM.render(and finally we write our App component as simple as:, document.getElementById("app"));
import React, { Component } from "react"; class App extends Component { render() { return ( <div> <h1>My React App</h1> </div> ); } } export default App;Now we can run our script by npm start, where start is defined by:
"start": "webpack-dev-server --mode development --open --hot"where open means open on save, and --hot works similar to --watch. Moreover, if we build our application in IIS, then webpack-dev-server can be replaced just by webpack.
My next target is to study how react and .net MVC interact to each other, i.e., using react in ASP.net framework.
No comments:
Post a Comment