In this tutorial we will create a React App from scratch with webpack
, we wont be using the create-react-app
command, we will go through each and every step required for setting up react app with webpack, babel and other npm modules.
Below is the set up before starting this tutorial
Following are the steps for creating a react app
"my_app"
on desktop vscode
open "my_app"
folder, "File-->Open Folder-->my_app"vscode
open New Terminal, "Terminal-->New Terminal" npm init
in terminal and provide below details
npm init
package name: (my_app) my_app
version: (1.0.0) 1.0.0
description: React app with webpack
entry point: (index.js) index.js
test command: none
git repository: none
keywords: none
author: gcptutorials
license: (ISC) ISC
About to write to C:\Users\gcptutorials\Desktop\my_app\package.json:
{
"name": "my_app",
"version": "1.0.0",
"description": "React app with webpack",
"main": "index.js",
"scripts": {
"test": "none"
},
"repository": {
"type": "git",
"url": "none"
},
"keywords": [
"none"
],
"author": "gcptutorials",
"license": "ISC"
}
Is this OK? (yes) yes
react
and react-dom
packages
npm install react react-dom
babel
packages as dev dependency
npm install --save-dev babel-core babel-loader@7 babel-preset-env babel-preset-react
webpack
packages as dev dependency
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin
"my_App"
, create folder with name "src"
"src"
create two files "index.js"
and "index.html"
"src"
create a folder with name "components"
"components"
create a file "App.js"
"my_App"
, create a file ".babelrc"
"my_App"
, create a file "webpack.config.js"
By now we should be having directory structure as shown below
Write below content in file ".babelrc"
{
"presets":["env", "react"]
}
Write below code in file "webpack.config.js"
const path = require("path");
const HtmlWebPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
path: path.join(__dirname, "dist"),
filename: "main.js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: "babel-loader",
},
],
},
plugins: [new HtmlWebPlugin({ template: "./src/index.html" })],
};
Write below code in file "index.html"
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id='root'></div>
</body>
</html>
Write below code in file "index.js"
import React from 'react';
import ReactDom from 'react-dom'
import App from './components/App'
ReactDom.render(<App />, document.getElementById('root'))
Write below code in file "App.js"
import React, { Component } from 'react';
class App extends Component {
render()
{
return(
<div>
<h2> My First app from scratch with webpack and React</h2>
</div>
)
}
}
export default App;
Finally in file "package.json"
in "scripts"
section add below line
"start" : "webpack-dev-server --mode development --hot"
Execute below command in terminal
npm start
Open "http://localhost:8080" in browser, you should see app running
Category: WebDev