React with TypeScript項目框架搭建

我們采用Create React App創(chuàng)建項目,并支持TypeScript。

項目初始化

  1. 創(chuàng)建項目
    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. 配置導(dǎo)入模塊目錄
    tsconfig相關(guān)配置:"baseUrl": "src"

網(wǎng)絡(luò)請求

基于axios進(jìn)行網(wǎng)絡(luò)請求封裝。對網(wǎng)絡(luò)請求返回進(jìn)行攔截,如果沒有登陸跳轉(zhuǎn)到登陸頁;如果請求出錯彈出錯誤提示。示例代碼:

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);
    }
  },
);

動態(tài)路由

根據(jù)后臺返回的菜單數(shù)據(jù)動態(tài)生成菜單??蓞⒖迹?a href="http://www.itdecent.cn/p/c3f51bfdda9c" target="_blank">http://www.itdecent.cn/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 ? <C {...this.props} /> : null;
    }
  }
  return Comp;
}

添加less支持

Create React App默認(rèn)不支持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
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容