umi+Ant Design Mobile+rem搭建移动端H5框架

1.创建项目(我用的umi4)

pnpm dlx create-umi@latest

2.安装Ant Design Mobile

pnpm add antd-mobile
pnpm add antd-mobile-icons //安装Icon图标

3.安装postcss-px-to-viewport

pnpm add -D postcss-px-to-viewport

4.配置 /.umirc.ts

import path from 'path';
import { defineConfig } from 'umi';
import routes from './routes';

export default defineConfig({
  ...routes,
  npmClient: 'pnpm',
  proxy: {
    '/api': {
      target: '需要代理的地址',
      changeOrigin: true,
      pathRewrite: { '^': '' },
    },
  },
  alias: {
    '@': path.resolve(__dirname, 'src'),
  },
  extraPostCSSPlugins: [
    require('postcss-px-to-viewport')({
      unitToConvert: 'px',
      viewportWidth: 320,
      unitPrecision: 5,
      propList: ['*'],
      viewportUnit: 'vw',
      fontViewportUnit: 'vw',
      selectorBlackList: [],
      minPixelValue: 1,
      mediaQuery: false,
      replace: true,
      exclude: [],
      landscape: false,
      landscapeUnit: 'vw',
      landscapeWidth: 568,
    }),
  ],
});

5.路由

//index.tsx
import { defineConfig } from 'umi';
export default defineConfig({
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    { path: '/home', component: './home' },
    { path: '/profile', component: './profile' },
    { path: '/detail', component: './detail' },
  ],
});

//index.less
.tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

6.页面配置(/src/layouts/index.tsx)

import { Badge, TabBar } from 'antd-mobile';
import { AppOutline, UserOutline } from 'antd-mobile-icons';
import { history, Outlet, useLocation } from 'umi';
import styles from './index.less';

export default function Layout(props) {
  const location = useLocation();
  const { pathname } = location;
  console.log('pathname', pathname);

  const tabsShow: string[] = ['/home', '/profile'];
  const tabs = [
    {
      key: '/home',
      title: '首页',
      icon: <AppOutline />,
      badge: Badge.dot,
    },
    {
      key: '/profile',
      title: '我的',
      icon: <UserOutline />,
    },
  ];
  if (!tabsShow.includes(pathname)) {
    return <Outlet />;
  }
  return (
    <div className={styles.navs}>
      <Outlet />
      <div className={styles.tabbar}>
        <TabBar safeArea onChange={(value) => history.push(value)}>
          {tabs.map((item) => (
            <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
          ))}
        </TabBar>
      </div>
    </div>
  );
}

5.请求拦截

/src 下新建app.tsx
 /*
 * @Author: muge
 * @Date: 2021-12-29 18:39:27
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-30 17:11:32
 */
import { RequestConfig } from 'umi';
const token='JWT ...'
const requestInterceptor = (url: string, options: any) => {
  options.headers = {
    Authorization: token,
  };
  options.interceptors = true;
  return {
    url,
    options,
  };
};
export const request: RequestConfig = {
  requestInterceptors: [requestInterceptor],
};

你可能感兴趣的:(react,前端,typescript,javascript,前端)