首页 > 其他分享 >react ts

react ts

时间:2023-01-18 16:14:37浏览次数:72  
标签:less config ts react export import postcss

 前提

你需要准备好node.js版本不低于6.14.8 和 git

文章内容比较长(保姆级别教程),全是干货,请耐心看完

通过create-react-app脚手架搭建项目

1.第一步

        注: 项目名称不可以出现大写字母

  • 打开文件夹,呼出cmd,输入搭建命令npx create-react-app testproject --template typescript
  • npx create-react-app testproject(项目名称) --template typescript

出现Happy hacking! 就说明项目搭建成功

 打开vscode查看项目

 

当项目中出现tsx 就说明项目搭建成功

然后启动项目  npm start  / npm run start

 

二、配置路由 

下载路由

npm i [email protected] react-router-config @types/react-router-config @types/react-router-dom -S
 

src目录下创建views文件夹,views内创建Home,Contact,About,Navbar四个tsx文件,其中Navbar用来控制路由,其他三个页面用来展示

Home:

  1.   import React, { Component } from "react";
  2.    
  3.   export default class Home extends Component {
  4.   render() {
  5.   return (
  6.   <div className="home">
  7.   <div className="container">
  8.   <h3 className="center"> Home页面</h3>
  9.   <p>欢迎来到首页</p>
  10.   </div>
  11.   </div>
  12.   );
  13.   }
  14.   }

Contact:

  1.   import React, { Component } from "react";
  2.    
  3.   export default class Contact extends Component {
  4.   render() {
  5.   return (
  6.   <div className="contact">
  7.   <div className="container">
  8.   <h3 className="center"> Contact页面</h3>
  9.   <p>欢迎来到联系我们页面!</p>
  10.   </div>
  11.   </div>
  12.   );
  13.   }
  14.   }

About:

  1.   import React, { Component } from "react";
  2.    
  3.   export default class About extends Component {
  4.   render() {
  5.   return (
  6.   <div className="about">
  7.   <div className="container">
  8.   <h3 className="center"> About页面</h3>
  9.   <p>欢迎来到关于我们页面!</p>
  10.   </div>
  11.   </div>
  12.   );
  13.   }
  14.   }

Navbar:

  1.   import React, { Component } from "react";
  2.    
  3.   export default class Navbar extends Component {
  4.   render() {
  5.   return (
  6.   <nav className="nav-wrapper">
  7.   <div className="list">
  8.   <ul>
  9.   <li><a href='/'>Home</a></li>
  10.   <li><a href='/about'>About</a></li>
  11.   <li><a href='/contact'>Contact</a></li>
  12.   </ul>
  13.   </div>
  14.   </nav>
  15.   )
  16.   }
  17.   }

 创建完成后

 src目录下创建routes文件夹,同时创建index.ts,使用RouteConfig对路由进行统一管理

  1.   // 导入路由组件
  2.   import Home from '../views/Home'
  3.   import About from '../views/About'
  4.   import Contact from '../views/Contact'
  5.   // 导入路由管理工具
  6.   import {RouteConfig} from 'react-router-config'
  7.    
  8.   const routes:RouteConfig = [
  9.   {
  10.   path:'/',
  11.   exact:true,
  12.   component:Home
  13.   },
  14.   {
  15.   path:'/about',
  16.   exact:true,
  17.   component:About
  18.   },
  19.   {
  20.   path:'/contact',
  21.   exact:true,
  22.   component:Contact
  23.   }
  24.   ]
  25.    
  26.   export default routes;

 

  App.tsx中引入Routes,Navbar和路由管理工具

  1.   import React from "react";
  2.   // 引入路由导航栏
  3.   import Navbar from "./views/Navbar";
  4.   // 引入routes组件
  5.   import routes from "./routes";
  6.   // 引入包管理工具
  7.   import { renderRoutes, RouteConfig } from "react-router-config";
  8.   import "./App.css";
  9.    
  10.   function App() {
  11.   return (
  12.   <div className="App">
  13.   <Navbar />
  14.    
  15.   {/* 设置routes的类型为RouteConfig[],否则报错 */}
  16.   {renderRoutes(routes as RouteConfig[])}
  17.   </div>
  18.   );
  19.   }
  20.    
  21.   export default App;

 根目录index.tsx中这样定义

  1.   import React from "react";
  2.   import ReactDOM from "react-dom";
  3.   import "./index.css";
  4.   import App from "./App";
  5.   import reportWebVitals from "./reportWebVitals";
  6.   import { BrowserRouter as Router } from "react-router-dom";
  7.    
  8.   ReactDOM.render(
  9.   <React.StrictMode>
  10.   <Router>
  11.   <App />
  12.   </Router>
  13.   </React.StrictMode>,
  14.   document.getElementById("root")
  15.   );
  16.    
  17.   // If you want to start measuring performance in your app, pass a function
  18.   // to log results (for example: reportWebVitals(console.log))
  19.   // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
  20.   reportWebVitals();

 路由配置完成启动项目

如果启动出现这种报错的话

  运行命令

npm i [email protected] -s
 

 再次重启项目

 给页面加点样

在App.css里面添加样式

  1.   * {
  2.   padding: 0;
  3.   margin: 0;
  4.   }
  5.    
  6.   h1 {
  7.   text-align: center;
  8.   font-size: 45px;
  9.   font-family: Arial, Helvetica, sans-serif;
  10.   color: rgb(6, 0, 32);
  11.   padding: 40px;
  12.   }
  13.    
  14.   .list {
  15.   display: flex;
  16.   justify-content: center;
  17.   width: 100%;
  18.   }
  19.    
  20.   .list ul li {
  21.   list-style: none;
  22.   margin: 42px;
  23.   text-align: center;
  24.   }
  25.    
  26.   a {
  27.   text-decoration: none;
  28.   color: rgb(0, 0, 0);
  29.   font-size: 18px;
  30.   font-family: Arial, Helvetica, sans-serif;
  31.   padding: 14px 25px;
  32.   background-color: transparent;
  33.   border: 2px solid rgb(12, 0, 66);
  34.   }
  35.    
  36.   a:hover {
  37.   background-color: rgb(12, 0, 66);
  38.   color: rgb(255, 255, 255);
  39.   }

 

三、配置less 

   暴露配置方式

                 因为有git 所以 需要依次输入以下三条命令

  1.   git add .
  2.    
  3.   git commit -m '暴露'
  4.    
  5.   npm run eject

此时项目多出了config文件夹

 安装lessless-loader

npm i less less-loader -S
 

找到config目录下的webpack.config.js文件,在50-70行之间有个cssRegex,在此处添加 

  1.   // less
  2.   const lessRegex = /\.less$/;
  3.   const lessModuleRegex = /\.module\.less$/;

 webpack.config.js文件500多行有个sassRegex,模仿写对应的lessRegex

  1.   // less
  2.   {
  3.   test: lessRegex,
  4.   exclude: lessModuleRegex,
  5.   use: getStyleLoaders(
  6.   {
  7.   importLoaders: 2,
  8.   sourceMap: isEnvProduction && shouldUseSourceMap,
  9.   },
  10.   'less-loader'
  11.   ),
  12.   sideEffects: true,
  13.   },
  14.   // less
  15.   {
  16.   test: lessModuleRegex,
  17.   use: getStyleLoaders(
  18.   {
  19.   importLoaders: 2,
  20.   sourceMap: isEnvProduction && shouldUseSourceMap,
  21.   modules: true,
  22.   getLocalIdent: getCSSModuleLocalIdent,
  23.   },
  24.   'less-loader'
  25.   ),
  26.   },

 重新启动项目npm start,在views中创建less文件并引入

 

附:如果出现报错

 说明react版本是18的版本 所以我们要降低版本

npm install [email protected] [email protected] --save
 

 

四、配置sass(选配)

     通过create-react-app创建的react项目,其实是默认已经配置好sass的,所以我们先尝试在项目中引入sass文件

 跟着步骤会出现两个错误

红色区域是两个样式撞了 所以less和sass二选一 (之后找到解决方法会解决

中间区域一般报的是

 解决方法:执行下面的命令   之后重启项目即可

npm i sass -s
 

 

五、配置px2rem自适应

   暴露config方式

        1. 安装lib-flexible、pxtorem,postcss

npm i lib-flexible postcss-pxtorem postcss postcss-loader postcss-preset-env postcss-flexbugs-fixes -s
 

      2.配置config/webpack.config.js,在config目录下找到webpack.config.js文件,

         加上配置的内容

  1.   // 配置rem
  2.   const px2rem = require('postcss-pxtorem');

    然后再下面代码中加入这行代码(里面大小可以自行调配 如你常用375的设计图就将   

rootValue: 75  => rootValue: 37.5  (根据个人喜好))

     找到当前页面下的128行左右 或者篮框下面

 750 设计图代码

  1.   {
  2.   // Options for PostCSS as we reference these options twice
  3.   // Adds vendor prefixing based on your specified browser support in
  4.   // package.json
  5.   loader: require.resolve('postcss-loader'),
  6.   options: {
  7.   postcssOptions: {
  8.   // Necessary for external CSS imports to work
  9.   // https://github.com/facebook/create-react-app/issues/2677
  10.   ident: 'postcss',
  11.   config: false,
  12.   plugins: !useTailwind
  13.   ? [
  14.   'postcss-nested',
  15.   'postcss-flexbugs-fixes',
  16.   [
  17.   'postcss-preset-env',
  18.   {
  19.   autoprefixer: {
  20.   flexbox: 'no-2009',
  21.   },
  22.   stage: 3
  23.   },
  24.   ],
  25.   // Adds PostCSS Normalize as the reset css with default options,
  26.   // so that it honors browserslist config in package.json
  27.   // which in turn let's users customize the target behavior as per their needs.
  28.   px2rem({
  29.   rootValue: 75, //设计稿宽/10
  30.   selectorBlackList : [], //过滤
  31.   propList : ['*'],
  32.   minPixelValue: 2,
  33.   exclude: /node_modules/i
  34.   }), //设计稿根据750px(iphone6)
  35.   'postcss-normalize',
  36.   ]
  37.   : [
  38.   'tailwindcss',
  39.   'postcss-flexbugs-fixes',
  40.   [
  41.   'postcss-preset-env',
  42.   {
  43.   autoprefixer: {
  44.   flexbox: 'no-2009',
  45.   },
  46.   stage: 3,
  47.   },
  48.   ],
  49.   px2rem({
  50.   rootValue: 75,//设计稿宽/10
  51.   selectorBlackList : [], //过滤
  52.   propList : ['*'],
  53.   minPixelValue: 2,
  54.   exclude: /node_modules/i
  55.   }), //设计稿根据750px(iphone6)
  56.   ],
  57.   },
  58.   sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
  59.   },
  60.   },

375设计稿

  1.   {
  2.   // Options for PostCSS as we reference these options twice
  3.   // Adds vendor prefixing based on your specified browser support in
  4.   // package.json
  5.   loader: require.resolve('postcss-loader'),
  6.   options: {
  7.   postcssOptions: {
  8.   // Necessary for external CSS imports to work
  9.   // https://github.com/facebook/create-react-app/issues/2677
  10.   ident: 'postcss',
  11.   config: false,
  12.   plugins: !useTailwind
  13.   ? [
  14.   'postcss-nested',
  15.   'postcss-flexbugs-fixes',
  16.   [
  17.   'postcss-preset-env',
  18.   {
  19.   autoprefixer: {
  20.   flexbox: 'no-2009',
  21.   },
  22.   stage: 3
  23.   },
  24.   ],
  25.   // Adds PostCSS Normalize as the reset css with default options,
  26.   // so that it honors browserslist config in package.json
  27.   // which in turn let's users customize the target behavior as per their needs.
  28.   px2rem({
  29.   rootValue: 37.5, //设计稿宽/10
  30.   selectorBlackList : [], //过滤
  31.   propList : ['*'],
  32.   minPixelValue: 2,
  33.   exclude: /node_modules/i
  34.   }), //设计稿根据750px(iphone6)
  35.   'postcss-normalize',
  36.   ]
  37.   : [
  38.   'tailwindcss',
  39.   'postcss-flexbugs-fixes',
  40.   [
  41.   'postcss-preset-env',
  42.   {
  43.   autoprefixer: {
  44.   flexbox: 'no-2009',
  45.   },
  46.   stage: 3,
  47.   },
  48.   ],
  49.   px2rem({
  50.   rootValue: 37.5,//设计稿宽/10
  51.   selectorBlackList : [], //过滤
  52.   propList : ['*'],
  53.   minPixelValue: 2,
  54.   exclude: /node_modules/i
  55.   }), //设计稿根据750px(iphone6)
  56.   ],
  57.   },
  58.   sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
  59.   },
  60.   },

src目录下找到index入口文件,在文件上面加入

import 'lib-flexible';
 

找到public/index.html文件,替换如下代码:

<meta content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport"/>
 

重新运行项目,一般就可以看到px转rem了

 存在问题:当设备宽度超过540后,样式就固定在540不再改变了

解决方法:在node-modules => lib-flexible => flexible.js中找到refreshRem修改其中的width值为设计稿宽度即可

 

 六、配置axios和反向代理

1. 安装axios 和 http-proxy-middleware(后面反向代理会用到)

npm i axios http-proxy-middleware -s
 

2.在src目录下创建api文件夹,然后创建 index.ts 和 request.ts 文件

       index.ts

  1.    
  2.   import {Service} from './request';
  3.   //获取汽车列表
  4.   export function getCarList(config: { page: string; }){
  5.   const params = new URLSearchParams()
  6.   params.append('page',config.page);
  7.    
  8.   return Service({
  9.   url:'./api/getCarList',
  10.   data:params
  11.   })
  12.   }

      request.ts

  1.    
  2.    
  3.   import axios from "axios";
  4.    
  5.   declare module 'axios' {
  6.   export interface AxiosResponse<T = any> extends Promise<T> {}
  7.   }
  8.    
  9.   export const Service = axios.create({
  10.   timeout: 3000, //延迟时间
  11.   method: "POST",
  12.   headers: {
  13.   "pc-token": "4a82b23dbbf3b23fd8aa291076e660ec",
  14.   "content-Type": "application/x-www-form-urlencoded",
  15.   },
  16.   });
  17.    
  18.   //请求拦截
  19.   Service.interceptors.request.use((config) => config);
  20.    
  21.   //响应拦截
  22.   Service.interceptors.response.use(
  23.   (response) => response.data,
  24.   (err) => console.log(err)
  25.   );

3. 配置代理,可以访问到后台的服务器地址

        在src文件夹中创建setupProxy.js内容配置如下

  1.   const {createProxyMiddleware} = require('http-proxy-middleware');
  2.    
  3.   module.exports = function(app) {
  4.   app.use('/api', createProxyMiddleware({
  5.   target: 'http://www.ibugthree.com/oldcar/',//后台服务器地址
  6.   changeOrigin: true,
  7.   pathRewrite: {
  8.   '^/api': '',
  9.   },}))
  10.   };

 在新版本中已经默认设置代理的文件夹名为setupProxy.js

 到这里所有配置就基本完成,在组件中调用即可

         Contact.tsx:

  1.   import React, { Component } from "react";
  2.   import "./contact.scss";
  3.   //导入要使用的接口
  4.   import { getCarList } from "../api/index";
  5.    
  6.   export default class Contact extends Component {
  7.   // 定义方法
  8.   getList() {
  9.   getCarList({ page: "1" }).then((res) => console.log(res));
  10.   }
  11.   render() {
  12.   return (
  13.   <div className="contact">
  14.   <div className="container">
  15.   <h3 className="center"> Contact页面</h3>
  16.   <p>欢迎来到联系我们页面!</p>
  17.   {/* 点击事件调用 */}
  18.   <button onClick={this.getList}>获取数据</button>
  19.   </div>
  20.   </div>
  21.   );
  22.   }
  23.   }

配完重启项目即可

 

 七、配置redux

                   1.安装redux

npm i redux react-redux -s
 

     在src路径下创建store文件夹,文件假中创建两个文件action.ts和index.ts两个文件

      action中定义type,然后返回设置状态的type和函数

action.ts

  1.   export const SET_AGE = "set_age";
  2.   export const SET_NAME = "set_name";
  3.    
  4.   export const setAge = function (n: number) {
  5.   return {
  6.   type: SET_AGE,
  7.   n: n,
  8.   };
  9.   };
  10.   export const setName = function (name: string) {
  11.   return {
  12.   type: SET_NAME,
  13.   name: name,
  14.   };
  15.   };

            index文件中取出redux中的createStore,以及action中的type,最后需要将createStore返回出去,并且需要传递一个函数,定义这个函数时有两个参数,一个是状态,一个是action,使用switch判断action中的type,当所有条件都不成立时,将所有的状态返回,有条件成立时,就通过扩展运算符将state展开,并且对age进行操作(...state);
 

index.ts

  1.   import { createStore } from "redux";
  2.   import { SET_AGE, SET_NAME } from "./action";
  3.    
  4.   interface User {
  5.   name: string;
  6.   age: number;
  7.   }
  8.    
  9.   const common: User = {
  10.   name: "张三123",
  11.   age: 18,
  12.   };
  13.    
  14.   function user(state = common, action: any) {
  15.   switch (action.type) {
  16.   case SET_AGE:
  17.   return {
  18.   ...state,
  19.   age: state.age + action.n,
  20.   };
  21.   case SET_NAME:
  22.   return {
  23.   ...state,
  24.   name: action.name,
  25.   };
  26.   default:
  27.   return state;
  28.   }
  29.   }
  30.    
  31.   export default createStore(user);

 在主入口文件index.tsx中进行redux的连接和store的引用

  1.   import React from "react";
  2.   import ReactDOM from "react-dom";
  3.   import "./index.css";
  4.   import App from "./App";
  5.   import reportWebVitals from "./reportWebVitals";
  6.   // 引入路由组件
  7.   import { BrowserRouter as Router } from "react-router-dom";
  8.   // 引入移动端自适应
  9.   import "lib-flexible";
  10.   //引入rootReducer组件
  11.   import { Provider } from "react-redux";
  12.   import store from "./store";
  13.    
  14.   ReactDOM.render(
  15.   <React.StrictMode>
  16.   {/* provider组件将所有的组件包裹起来,用绑定属性的形式绑定store到组件中 */}
  17.   <Provider store={store}>
  18.   <Router>
  19.   <App />
  20.   </Router>
  21.   </Provider>
  22.   </React.StrictMode>,
  23.   document.getElementById("root")
  24.   );
  25.    
  26.   reportWebVitals();

 在App中进行配置

  1.   import React from "react";
  2.   // 引入路由导航栏
  3.   import Navbar from "./views/Navbar";
  4.   // 引入routes组件
  5.   import routes from "./routes";
  6.   // 引入包管理工具
  7.   import { renderRoutes, RouteConfig } from "react-router-config";
  8.   import "./App.css";
  9.   // 引入connect连接组件
  10.   import {connect} from "react-redux"
  11.    
  12.    
  13.   function App() {
  14.   return (
  15.   <div className="App">
  16.   <Navbar />
  17.   {/* 设置routes的类型为RouteConfig[],否则报错 */}
  18.   {renderRoutes(routes as RouteConfig[])}
  19.   </div>
  20.   );
  21.   }
  22.    
  23.   //进行连接
  24.   export default connect((props,state)=>Object.assign({},props,state),{})(App);

 组件中使用redux

  •     引入connect和action中的方法

  •     定义props和state类型

  •     修改render中的html结构,定义属性和方法调用

  •     connect连接属性并导出

About.tsx:

  1.   import React, { Component } from "react";
  2.   import "./about.less";
  3.   // redux
  4.   import { connect } from "react-redux";
  5.   import { setName, setAge } from "../store/action";
  6.    
  7.   interface Props {
  8.   setAge: Function;
  9.   setName: Function;
  10.   age: number;
  11.   name: string;
  12.   }
  13.    
  14.   interface State {}
  15.    
  16.   class About extends Component<Props,State> {
  17.   refs:any = React.createRef()
  18.   // eslint-disable-next-line @typescript-eslint/no-useless-constructor
  19.   constructor(props:Props){
  20.   super(props)
  21.   }
  22.   changeAge(){
  23.   this.props.setAge(1);
  24.   console.log(this.props);
  25.   }
  26.   changeName(){
  27.   let name:number = this.refs.value
  28.   this.props.setName(name)
  29.   console.log(this.refs);
  30.   this.refs.value = ''
  31.   }
  32.   render() {
  33.   return (
  34.   <div className="about">
  35.   <div className="container">
  36.   <h3 className="center"> About页面</h3>
  37.   <p>欢迎来到关于我们页面!</p>
  38.   </div>
  39.   <div>
  40.   <p>名字是:{this.props.name}</p>
  41.   <input ref={(input: HTMLInputElement) => this.refs = input} type="text" />
  42.   <button onClick={this.changeName.bind(this)}>修改姓名</button>
  43.   <p>年龄是:{this.props.age}</p>
  44.   <button onClick={this.changeAge.bind(this)}>修改年龄</button>
  45.   </div>
  46.   </div>
  47.   );
  48.   }
  49.   }
  50.    
  51.   export default connect((props,state)=>Object.assign({},props,state),{
  52.   setAge,setName
  53.   })(About);

 

 八、配置别名(选配)

           打开 config 文件夹下的 webpack.config.js 文件

           ctrl + f 搜索alias,替换这个alias,代码如下:

  1.   alias: {
  2.   // Support React Native Web
  3.   // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  4.   'react-native': 'react-native-web',
  5.   // Allows for better profiling with ReactDevTools
  6.   ...(isEnvProductionProfile && {
  7.   'react-dom$': 'react-dom/profiling',
  8.   'scheduler/tracing': 'scheduler/tracing-profiling',
  9.   }),
  10.   ...(modules.webpackAliases || {}),
  11.   // 文件路径别名
  12.   '@': path.resolve(__dirname, '../src'),
  13.   '@view': path.resolve(__dirname, '../src/view'),
  14.   },

 需要特别注意的是: webpack配置进行改动后,都需要重新启动项目,不然不生效

 

九、配置antd-mobile (选配)

     1.安装antd-mobile ui组件库类似于element-ui

  1.   npm install antd-mobile
  2.   //或
  3.   yarn add antd-mobile

     2.在项目中Home.tsx文件中导入要使用的组件

            Home.tsx:

  1.   import React, { Component } from "react";
  2.   //使用组件直接在组件中进行使用即可
  3.   import { Button } from 'antd-mobile';
  4.    
  5.   export default class Home extends Component {
  6.   render() {
  7.   return (
  8.   <div className="home">
  9.   <div className="container">
  10.   <h3 className="center"> Home页面</h3>
  11.   <p>欢迎来到首页</p>
  12.   <Button color='primary'>按钮</Button>
  13.   </div>
  14.   </div>
  15.   );
  16.   }
  17.   }

 完成之后,你就能在react项目使用antd-mobile的样式文件进行构建自己的页面了

 

以上就是react+typescript+router+redux+less+px2rem自适应+sass+axios反向代理+别名@+Antd-mobile配置的所有详细步骤

 

 有问题请及时沟通!

 

标签:less,config,ts,react,export,import,postcss
From: https://www.cnblogs.com/wj204/p/17060053.html

相关文章