从零搭建React框架--第一章:create-react-ap

2021-11-10  本文已影响0人  被偷的贼

目录

引言
第一章:项目创建、antd、less
第二章:路由拦截、路由嵌套
第三章:状态管理 Redux
第四章:网络请求、代理、mockjs
第五章:webpack配置
第六章:Eslint

源码地址

https://github.com/dxn920128/cms-base

创建项目

本次项目使用create-react-app命令进行创建

// npm 全局安装create-react-app
npm install -g create-react-app
// 创建项目
npx create-react-app react-demo --typescript
// yarn
yarn create react-app react-demo --template typescript

webpack配置

使用 create-react-app初始化项目后,需要对webpack进行配置。webpack配置包含:less进行antd主题配置、别名、请求代理、mocker数据等等。
1、使用 npm run eject 命令将所有内建的配置暴露出来。
2、本次推荐使用 craco 进行配置。

npm install -D @craco/craco  @babel/plugin-proposal-decorators babel-plugin-import craco-less 
npm install antd

1、修改package.json启动项。

 "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test"
  },

2、创建craco.config.js并进行配置

const CracoLessPlugin = require('craco-less')
module.exports = {
  plugins: [
    {
      plugin: CracoLessPlugin,//引入less
      options: {
        lessLoaderOptions: {
          lessOptions: {
            javascriptEnabled: true //js修改主题样式
          }
        }
      }
    }
  ],
  babel: {
    plugins: [
      ['@babel/plugin-proposal-decorators', { legacy: true }], //装饰器
      [
        'import',//按需引入antd 样式
        {
          'libraryName': 'antd',
          'libraryDirectory': 'es',
          'style': true
        }
      ]
    ]
  },
};

3、定义antd全局样式,在创建 index.less文件

src/assets/style/index.less

@import "~antd/dist/antd.less";

@primary-color: #1890ff; //主题色
@border-radius-base: 2px;
@link-color: #1890ff; // 链接色
@success-color: #52c41a; // 成功色
@warning-color: #faad14; // 警告色
@error-color: #f5222d; // 错误色
@font-size-base: 14px; // 主字号
@heading-color: rgba(0, 0, 0, 0.85); // 标题色
@text-color: rgba(0, 0, 0, 0.65); // 主文本色
@text-color-secondary: rgba(0, 0, 0, 0.45); // 次文本色
@disabled-color: rgba(0, 0, 0, 0.25); // 失效色
@border-radius-base: 2px; // 组件/浮层圆角
@border-color-base: #d9d9d9; // 边框色
@layout-header-background: #ffffff;
@layout-body-background: #ffffff;

@box-shadow-base: 0 3px 6px -4px rgba(0, 0, 0, 0.12),
  0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05); // 浮层阴影

4、全局引入index.less

import React from 'react'
import ReactDOM from 'react-dom'
import reportWebVitals from './reportWebVitals'
import { Provider } from 'react-redux'
import store from './store/index'
import { ConfigProvider } from 'antd'
import zhCN from 'antd/lib/locale/zh_CN'
import AppRouter from './pages/frame/appRouter'
import './assets/style/index.less'

ReactDOM.render(
  <ConfigProvider locale={zhCN}>
    <Provider store={store}>
      <AppRouter />
    </Provider>
  </ConfigProvider>,
  document.getElementById('root')
)
上一篇 下一篇

猜你喜欢

热点阅读