React with TypeScript项目框架搭建

我们采用Create React App创建项目,并支持TypeScript。

项目初始化

  1. 创建项目
    npx create-react-app my-app --template typescript
  2. 弹出配置
    yarn run eject
  3. 添加ESLint
    yarn add prettier --dev --exact
    yarn add --dev eslint-config-prettier eslint-plugin-prettier
    package.json eslint配置:
"eslintConfig": {
    "extends": [
      "react-app",
      "plugin:@typescript-eslint/recommended",
      "prettier/@typescript-eslint",
      "plugin:prettier/recommended"
    ]
  }
  1. 配置导入模块目录
    tsconfig相关配置:"baseUrl": "src"

网络请求

基于axios进行网络请求封装。对网络请求返回进行拦截,如果没有登陆跳转到登陆页;如果请求出错弹出错误提示。示例代码:

service.interceptors.response.use(
  (response): any => {
    if (response.data.status === "0") {
      return response.data.data;
    } else if (response.data.status + "" === "2000") {
      store.dispatch(routerRedux.push("/login"));
      return Promise.reject("not login");
    } else {
      let error = getApiErrorByStatus(response.data.status);
      notificationError(error, response.data.detailMessage);
      return Promise.reject(response);
    }
  },
);

动态路由

根据后台返回的菜单数据动态生成菜单。可参考:https://www.jianshu.com/p/c3f51bfdda9c

路由懒加载

webpack的import()方法可以将模块单独打包。示例代码:

function getAsyncComponent(
  importModule: any,
  isDefault: any = true,
  componentName?: any
) {
  class Comp extends Component {
    state = { comp: null };
    componentDidMount() {
      importModule().then((module: any) => {
        let comp = isDefault ? module.default : module[componentName];
        this.setState({ comp: comp });
      });
    }
    render() {
      let C: any = this.state.comp;
      return C ?  : null;
    }
  }
  return Comp;
}

添加less支持

Create React App默认不支持less,安装less,less-loader,webpack配置:

{
              test: lessRegex,
              exclude: lessModuleRegex,
              use: [
                ...getStyleLoaders(
                  {
                    importLoaders: 2,
                    sourceMap: isEnvProduction && shouldUseSourceMap
                  },
                  "less-loader",
                  {
                    javascriptEnabled: true
                  }
                ),
                {
                  loader: "style-resources-loader",
                  options: {
                    patterns: styleResourcePatterns
                  }
                }
              ],
              sideEffects: true
}

你可能感兴趣的:(React with TypeScript项目框架搭建)