React系列一 | 搭建React项目

Table of Contents

创建项目


npx create-react-app my-app

创建完成后会有完整的工程目录

git 仓库等各种都已经创建好。默认的是 React 的介绍页面。可以在这个基础上进行修改。

项目结构

  1. index.js 为入口文件,创建了一个根节点 root, 并对根节点进行渲染
  2. app.js 为具体应用的文件。
  3. public 中的 index.html 为 html 模板。
  4. reportWebVitals.js 为项目的监控文件。

使用 vite 重新搭建项目

起因是因为在后续的运行过程中发现报错 DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated
参考了 github 上的issueissue 后放弃使用 create-react-app

GitHub 项目地址和文档GitHub & 文档

搭建命令

npm create vite@latest  xxxx

文档中的搭建示例 接下来会让你选择要使用的框架和语言,包含了 vue、react 等。

使用 TailwindCss 装饰

对于没有前端基础的学习 css 头大,遂决定用 tailwindcss 来处理页面,最基本的应该没问题

文档地址: Tailwindcss 组件库

安装 TailwindCss

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
以上命令会在当前目录初始化 tailwindcss,创建tailwind.config.js文件
/** @type {import('tailwindcss').Config} */

export default {
  content: ["./src/**/*.{js,jsx,ts,tsx}"],
  theme: {
    extend: {},
  },
  plugins: ["prettier-plugin-tailwindcss"],
}
  • content 需要写关联文件的目录,React 的一般是 src,根据自己情况填写,
  • plugings 这个为插件,我在 vscode 中使用了 prettier,所以安装了插件支持
在项目根目录创建postcss.config.js文件
import tailwindcss from 'tailwindcss';
import autoprefixer from 'autoprefixer';

export default {
  plugins: [
    tailwindcss,
    autoprefixer,
  ],
};
在 index.css 文件中加入 TailwindCss
@tailwind base;
@tailwind components;
@tailwind utilities;

注意文件的引用要正确。创建的项目结构中,index.html为入口文件,index.html 中关联这main.jsx,main.jsx 中关联着index.css,index.css 文件中是 TailwindCss 的引用。要根据自己的文件内容修改。:down 以下是我的项目结构:

my-vite-project/
├── node_modules/
├── public/
│   └── vite.svg
├── src/
│   ├── components/
│   │   ├── Footer.jsx
│   │   ├── Header.jsx
│   │   └── MainContent.jsx
│   ├── App.jsx
│   ├── index.css
│   └── main.jsx
├── .gitignore
├── index.html
├── package.json
├── tailwind.config.js
├── postcss.config.js
└── vite.config.js

使用 prettier 格式化代码

useTabs: true
semi: false
singleQuote: true
quoteProps: consistent
jsxSingleQuote: false
trailingComma: all
bracketSpacing: true
bracketSameLine: true
arrowParens: always
proseWrap: preserve
htmlWhitespaceSensitivity: css
vueIndentScriptAndStyle: true
endOfLine: lf
embeddedLanguageFormatting: auto
singleAttributePerLine: false