前言
自己搭的脚手架,坑都是一步一步踩完的;
技术栈: react@16.6.0
/ react-router-dom@v4
/ webpack^4.23.1(babel7+)
闲话不多说,直入主题,有兴趣的可以瞧瞧,没兴趣的止步,节约您的时间.
问题列表
问题一:history
模式下,接口和请求冲突的问题
就是反向映射接口和请求的根路径重叠,如下:
proxy: {
'/': {
target: 'http://192.168.31.100/api/web',
changeOrigin: true,
secure: false,
}
},
这样映射会造成路由寻址不到,这个问题我遇到的时候,浪费了挺多时间,最后发现还是有解的;
网上大多数人的写法就是,加个prefix
(聚合一个前缀),然后用pathRewrite
重写请求路径
proxy: {
'/api': {
target: 'http://192.168.31.100/api/web',
changeOrigin: true,
secure: false,
pathRewrite: {
'^/api': '/' },
}
},
historyApiFallback: true
可这法子,不大适合我这边…能不能重叠又不影响,
翻了一些Stack Overflow
上的问答和文档,发现还是有的.
下面的写法就是先判断是html
请求还是其他请求,若是请求html
则不反向代理
proxy: {
'/': {
target: 'http://192.168.31.100/api/web',
changeOrigin: true,
secure: false,
// pathRewrite: { '^/api': '/' },
bypass: function(req, res, proxyOptions) {
if (req.headers.accept.indexOf('html') !== -1) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}
}
}
},
historyApiFallback: true
问题二: 如何非ts
下支持装饰器 , 以及常规的语法解析
因为用了mobx
,实在不想用高阶函数的写法(一堆括号)。
我是直接配置babelrc
的. 跟随最新babel 7
,装上这个依赖即可支持
- @babel/plugin-proposal-decorators – 装饰器支持
- @babel/plugin-syntax-dynamic-import – 动态引入相关代码,适用于代码分离
- babel/plugin-proposal-object-rest-spread –
...
的支持 - @babel/plugin-proposal-class-properties –
class
支持 - babel-plugin-import – 阿里出品的
css
按需加载 - react-hot-loader/babel – 配置
react-hot-loader
会用到
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"browsers": [
"last 3 versions",
"safari >= 7"
]
},
"modules": false,
"debug": false,
"useBuiltIns": "usage"
}
],
"@babel/preset-react"
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"@babel/plugin-proposal-class-properties",
{
"loose": true
}
],
"@babel/plugin-proposal-object-rest-spread",
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css"
}
],
"@babel/plugin-syntax-dynamic-import",
"react-hot-loader/babel"
]
}
问题三: mobx
实现路由基础鉴权
- model
import {
observable, action, computed, toJS } from 'mobx';
import API from 'services'; // axios的封装
class AuthModel {
constructor() {
}
// 登录请求
@action
requestLogin = async values => {
// 登录接口
const data = await API.post('/admin/login', values);
const AuthUserData = JSON.stringify(data);
window.localStorage.setItem('AuthUserData', AuthUserData);
window.location.href = '/';
};
// 退出登录
@action
requestLogout = async values => {
this.UserData = {
}; // 重置为空对象
this.isPermission = false;
window.