近日突然想用React开发个小东西。至于为什么用React就为它的小优点:速度快:在UI渲染过程中,React通过在虚拟DOM中的微操作来实现对实际DOM的局部更新。
由于好久没写了,还是打算重新发点东西,巩固自身的同时帮助他人。
废话不多说,进入主题,React从入门到···
今天将第一步,就讲下创建项目和SCSS、UI库吧。
我个人使用的yarn,所以下面的都以yarn示例。你可以用npm。
本人NODE版本:16.10.0
// 安装yarn
npm i -g corepack
yarn - v
1.22.19
一、安装 create-react-app
create-react-app 脚手架官网
PS:Create React App requires Node 14 or higher.(Create React App 需要 Node 14 或更高版本。)
npm install -g create-react-app
// -----------------------------------------------
create-react-app -v
Please specify the project directory:
create-react-app <project-directory>
For example:
create-react-app my-react-app
Run create-react-app --help to see all options.
二、创建项目
yarn create react-app react-ts-doc --template typescript
// 经过漫长的等待
cd .\react-ts-doc\
yarn start
Compiled successfully!
You can now view portable-system in the browser.
Local: http://localhost:3000
On Your Network: http://192.168.18.156:3000
Note that the development build is not optimized.
To create a production build, use npm run build.
webpack compiled successfully
三、添加开发基础所需依赖包(个人使用scss)
npm install node-sass --save
四、开发怎么能少的UI库呢,安装 Ant Design of React
// 1. 安装Ant Design of React https://2x.ant.design/docs/react/introduce-cn
npm install antd
// 2. 修改 src/App.scss 在文件顶部引入 antd/dist/antd.css
@import '~antd/dist/antd.css';
五、按需引入
上面的例子实际上加载了全部的 antd 组件的样式(对前端性能是个隐患)。
此时我们需要对 create-react-app 的默认配置进行自定义,这里我们使用 react-app-rewired (一个对 create-react-app 进行自定义配置的社区解决方案)。
引入 react-app-rewired 并修改 package.json 里的启动配置。
npm install react-app-rewired --save-dev
npm install babel-plugin-import --save-dev
npm install customize-cra --save-dev
npm i less
npm i -D less-loader
/* package.json */
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test --env=jsdom",
+ "test": "react-app-rewired test --env=jsdom",
}
然后在项目根目录创建一个 config-overrides.js 用于修改默认配置。
const {
override,
fixBabelImports,
} = require("customize-cra");
module.exports = override(
fixBabelImports("import", {
libraryName: "antd", libraryDirectory: "es", style: 'css' // change importing css to less
}),
);
修改 App.tsx
import React from 'react';
import { Button } from 'antd';
import './App.scss';
function App() {
return (
<div className="App">
<header className="App-header">
<Button type="primary">进入homePage</Button> <br />
<Button type="primary">进入aboutPage</Button>
</header>
</div>
);
}
export default App;
启动yarn start