📅  最后修改于: 2023-12-03 14:46:56.432000             🧑  作者: Mango
React JS is a popular JavaScript library used for building user interfaces. Every project requires some initial setup before we can start writing the code. The React JS empty build is the basic setup that allows you to start writing React JS applications from scratch. This guide will provide you with an understanding of the React JS empty build and how to set it up in your development environment.
Before you start, you should have the following installed:
Open your terminal or command prompt.
Create a new directory for your project.
Navigate to the project directory in your terminal.
Run the following command to initialize a new project:
npm init -y
This command will create a new package.json
file.
Run the following command to install React JS and React DOM:
npm install react react-dom
Run the following command to install Babel, which is a tool for converting modern JavaScript into a format that is compatible with old browsers:
npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader
Create a new file called webpack.config.js
in the root of your project directory.
Add the following code to webpack.config.js
:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
},
],
},
};
This code defines the entry point (./src/index.js
) and the output file (bundle.js
) of your project. It also tells Webpack to use the Babel loader for .js
and .jsx
files.
src
in the root of your project directory.index.html
in the root of your project directory.index.html
:<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React JS Empty Build</title>
</head>
<body>
<div id="app"></div>
<script src="./dist/bundle.js"></script>
</body>
</html>
This code defines the basic HTML structure of your application, including a div
element with the id
of app
. This is where all the React JS components will be rendered.
index.js
in the src
directory.index.js
:import React from 'react';
import ReactDOM from 'react-dom';
const App = () => {
return <h1>Hello, World!</h1>;
};
ReactDOM.render(<App />, document.getElementById('app'));
This code defines a simple React component (App
) that renders the text "Hello, World!". It then renders this component inside the div
element with the id
of app
.
Run the following command to build your project:
npx webpack
This command will bundle your code and create a bundle.js
file inside the dist
directory.
Open index.html
in your browser. You should see the text "Hello, World!".
In this guide, you learned how to set up the React JS empty build in your development environment. With this basic setup, you can start building React JS applications from scratch.