十、react脚手架
一、使用步骤
安装脚手架
1 npm i -g create-react-app
创建项目
1 create-react-app 项目名称
1 #也可以不用安装create-react-app创建项目 2 npx create-react-app my-app
清理创建好的项目中不需要的文件及文件夹
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8" /> 5 <!-- %PUBLIC_URL%代表public文件夹 --> 6 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> 7 <!-- 开启理想视口,用于移动端适配 --> 8 <meta name="viewport" content="width=device-width, initial-scale=1" /> 9 <!-- 用于配置浏览器页签+地址栏颜色(仅支持安卓手机浏览器) --> 10 <!-- <meta name="theme-color" content="#000000" /> --> 11 <!-- 描述网站信息 --> 12 <meta 13 name="description" 14 content="Web site created using create-react-app" 15 /> 16 <!-- 用于指定网页添加到手机主屏后的图标 --> 17 <!-- <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> --> 18 <!-- 应用夹壳配置文件manifest.json --> 19 <!-- <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> --> 20 <title>React App</title> 21 </head> 22 <body> 23 <div id="root"></div> 24 </body> 25 </html>
1 import React, { Component } from 'react' 2 3 export default class App extends Component { 4 render() { 5 return ( 6 <div> 7 react 8 </div> 9 ) 10 } 11 }
1 import React from 'react'; 2 import ReactDOM from 'react-dom'; 3 // import './index.css'; 4 import App from './App'; 5 // reportWebVitals用于记录页面性能 6 // import reportWebVitals from './reportWebVitals'; 7 8 ReactDOM.render( 9 // React.StrictMode检查代码 10 // <React.StrictMode> 11 <App />, 12 // </React.StrictMode>, 13 document.getElementById('root') 14 ); 15 16 // reportWebVitals();
二、目录划分
1 rcc
- 函数组件
1 rfc
折叠注释的部分:regin
1 function demo(){ 2 //#regin 3 //注释内容 4 //... 5 //#endregin 6 }
四、配置文件
1、webpack配置
react的webpack配置默认隐藏,修改配置需要使用第三方包
1 npm i -D customize-cra react-app-rewired
1 "scripts": { 2 "start": "react-app-rewired start", 3 "build": "react-app-rewired build", 4 "test": "react-app-rewired test", 5 "eject": "react-scripts eject" 6 }
1 const { 2 override, 3 addDecoratorsLegacy, 4 disableEsLint, 5 addBundleVisualizer, 6 addWebpackAlias, 7 adjustWorkbox, 8 fixBabelImports 9 } = require("customize-cra"); 10 const path = require("path"); 11 12 module.exports = override( 13 // 在webpack中禁用eslint 14 disableEsLint(), 15 16 // 添加webpack路径别名 17 addWebpackAlias({ 18 ["@"]: path.resolve("./src"), 19 }) 20 21 // 按需加载样式&组件代码 22 fixBabelImports("import", { 23 libraryName: "antd-mobile", 24 style: "css", 25 }) 26 );
2、配置代理
接口设置反向代理
1 npm i -D http-proxy-middleware
1 const proxy = require('http-proxy-middleware') 2 3 module.exports = function(app){ 4 app.use( 5 proxy('/api1', {//遇见/api1前缀的请求,就会触发该代理配置 6 //请求转发给谁 7 target: 'http://localhost:5000', 8 //控制服务器收到的请求头中Host的值 9 changeOrigin: true, 10 //去除请求前缀,重写请求路径 11 parthRewrite:{'^/api1':''} 12 }), 13 proxy('/api2', { 14 target: 'http://localhost:5001', 15 changeOrigin: true, 16 parthRewrite:{'^/api2':''} 17 }) 18 ) 19 }
1 npm i uuid
nanoid:库比较小
1 npm i nanoid
使用
1 import { nanoid } from 'nanoid' 2 // nanoid是个函数 3 console.log(nanoid())
六、打包运行
模拟服务器运行,安装serve
1 npm i serve -g
运行(以build文件为根路径)
1 serve build

浙公网安备 33010602011771号