我們采用Create React App創(chuàng)建項目,并支持TypeScript。
項目初始化
- 創(chuàng)建項目
npx create-react-app my-app --template typescript - 彈出配置
yarn run eject - 添加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"
]
}
- 配置導(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
}