React 是 facebook 推出的用于构建用户界面的前端 Javascript 库,中文官方地址为:https://react.docschina.org/。
React 具有声明式、组件化、一次学习,随处编写等特点,使用 React 可以将一些简短、独立的代码片段组合成复杂的 UI 界面,这些代码片段被称作“组件”。
环境搭建
官方文档中创建新的 React 应用:https://react.docschina.org/docs/create-a-new-react-app.html
手动搭建 webpack
创建项目目录并安装开发依赖:
- $ mkdirwebpack-react-project
- $ cd webpack-react-project/
- $ npm init -y
- npm install -D @babel/core@7.13.8@babel/preset-env@7.13.9 @babel/preset-react@7.12.13 babel-loader@8.2.2html-webpack-plugin@4.5.2 react@17.0.1 react-dom@17.0.1 webpack@4.46.0webpack-cli@3.3.12 webpack-dev-server@3.11.2
- + react@17.0.1
- + babel-loader@8.2.2
- + @babel/preset-env@7.13.9
- + webpack-dev-server@3.11.2
- + @babel/core@7.13.8
- + html-webpack-plugin@4.5.2
- + webpack-cli@3.3.12
- + @babel/preset-react@7.12.13
- + react-dom@17.0.1
- + webpack@4.46.0
项目创建完成,开发依赖安装成功后,package.json 内容如下:
- {
- "name":"webpack-react-project",
- "version":"1.0.0",
- "description":"",
- "main":"index.js",
- "scripts":{
- "test":"echo \"Error: no test specified\" && exit 1"
- },
- "keywords":[],
- "author":"",
- "license":"ISC",
- "devDependencies":{
- "@babel/core":"^7.13.8",
- "@babel/preset-env":"^7.13.9",
- "@babel/preset-react":"^7.12.13",
- "babel-loader":"^8.2.2",
- "html-webpack-plugin":"^4.5.2",
- "react":"^17.0.1",
- "react-dom":"^17.0.1",
- "webpack":"^4.46.0",
- "webpack-cli":"^3.3.12",
- "webpack-dev-server":"^3.11.2"
- }
- }
因为是自己进行手动安装配置,因此需要在项目根路径下手动创建 \webpack.config.js 文件,并做如下配置:
- const path =require('path')
- const HtmlWebpackPlugin =require('html-webpack-plugin')
- module.exports= {
- mode:'development',
- devtool:'none',
- entry:'./src/index.js',
- output: {
- filename:'main.js',
- path: path.resolve('dist')
- },
- devServer: {
- port:3000,
- hot:true
- },
- module: {
- rules: [
- {
- test:/\.js|jsx$/,
- exclude:/node_modules/,
- use: [
- {
- loader:'babel-loader',
- options: {
- presets: ['@babel/preset-env','@babel/preset-react']
- }
- }
- ]
- }
- ]
- },
- plugins: [
- newHtmlWebpackPlugin({
- template:'./src/index.html'
- })
- ]
- }
配置入口 \src\index.html
- <body>
- <divid="root"></div>
- </body>
配置入口 \src\index.js
- import React from'react'
- import { render } from'react-dom'
- // 自定义组件
- functionApp() {
- return<div>React</div>
- }
- render(<App />,document.getElementById('root'))
然后在 package.json 中添加配置选项:
- "scripts":{
- "test":"echo \"Error: no test specified\" && exit 1",
- "dev":"webpack-dev-server"
- },
然后在命令行中执行 npm run dev 就可以启动项目了。
使用官方脚手架create-react-app
官方脚手架 create-react-app 基于 webpack 进行打包构建。
脚手架构架项目:npx create-react-appmy-app
- > cd my-app
- > npm start
使用通用构建工具 Vite
Vite 本身就是一个构建工具,开发环境下不打包,生成环境使用 Rollup 进行打包。
执行命令 npm init vite@latest
- √ Project name: ...my-project
- ? Select a framework: » - Use arrow-keys. Return tosubmit.
- vanilla
- vue
- > react
- preact
- lit-element
- svelte
- ? Select a variant: » - Use arrow-keys. Return tosubmit.
- > react
- react-ts
- Scaffolding project in xxxxxxxxxxxxxx
- Done. Now run:
- cdvite-project
- npm install
- npm run dev