Skip to content
caijf edited this page May 14, 2025 · 11 revisions

Welcome to the vite-template-doly wiki!

常见问题

配置 mock 和 proxy

参考:vite-plugin-mock-dev-serverserver.proxy

兼容低版本浏览器

参考:@vitejs/plugin-legacy

下面是兼容 ie11 示例:

安装依赖

pnpm add @vitejs/plugin-legacy terser -D

vite.config.ts 配置

+ import legacy from '@vitejs/plugin-legacy';

export default defineConfig({
  plugins: [
    // ...,
+    legacy({
+      targets: ['ie >= 11'],
+      additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
+    }),
  ],

  // ...,
  build: {
    // ...,
+    minify: 'terser',
+    terserOptions: {
+      compress: {
+        warnings: false,
+        drop_console: true,
+        drop_debugger: true,
+        pure_funcs: ['console.log']
+      }
+    }
  },
-  esbuild: {
-    drop: isProd ? ['console', 'debugger'] : []
-  }
});

使用 keep-alive

参考:集成 keep-alive

环境变量和模式

参考:环境变量和模式

常见的使用场景是 本地开发(mock)、本地联调(proxy)。

一般在不同环境设置不同的请求 url

本地开发时,需要使用 mock 接口数据,将请求 url 设置为空,请求本地服务。

# .env.development
VITE_APP_API=''

本地联调时,需要通过 proxy 代理请求真实接口,避免跨域等问题。

# .env
VITE_APP_API='https://api.example.com'

除此之外,还可以用 .env.*.local 本地变量存放用户信息等,便于本地开发调试。

删除测试相关依赖和配置

  1. 删除 vitest.steup.ts src/pages/home/__snapshots__ src/pages/home/Home.test.tsx 文件

  2. vite.config.ts 删除配置

- /// <reference types="vitest" />

-  // https://cn.vitest.dev/guide/
-  test: {
-    environment: 'jsdom',
-    setupFiles: ['./vitest.setup.ts']
-  }
  1. package.json 删除依赖和脚本
"scripts": {
-  "test": "vitest"
},

"devDependencies": {
-  "@testing-library/jest-dom": "^6.4.5",
-  "@testing-library/react": "^15.0.7",
-  "@testing-library/user-event": "^14.5.2",
-  "jsdom": "^24.1.0",
-  "vitest": "^1.6.0",
}

关闭页面切换动画

src/router.tsx

const router = createHashRouter(
  createRoutesFromElements(
    <Route
      path="*"
      element={(
        <AnimatedRoutes
          routes={routes}
+         animated={false}
        />
      )}
    />
  )
);

非组件模块中如何跳转页面

参考:React Router

正常页面中的跳转

import { useNavigate } from 'react-router-dom'

function Component(){
  const navigate = useNavigate();
  return (
    <div>
      <a onClick={()=>{navigate('/path')}}></a>
    </div>
  )
}

非组件模块

utils/utils.ts

import router from '@/router';

function toLoginPage() {
  router.navigate('/login');
}

路由如何配置重定向

例如首页重定向到列表页, src/router.tsx

{
  index: true,
  element: <Navigate to="/repos/list" replace />,
  title: '首页'
}

开发时修改 src/router.tsx 文件,控制台出现警告信息

[vite] hmr invalidate /src/main.tsx Could not Fast Refresh ("true" export is incompatible). Learn more at https://github.com/vitejs/vite-plugin-react-swc#consistent-components-exports

这是因为 src/router.tsx 导出的不是一个组件,且只在修改该文件时产生该警告信息。暂时没有发现什么影响,可以先无视它。

使用 PWA

参考:vite-plugin-pwa

安装依赖

pnpm add vite-plugin-pwa -D

vite.config.ts 配置

+ import { VitePWA } from 'vite-plugin-pwa';


export default defineConfig({
  plugins: [
    // ...,
+  VitePWA({
+    registerType: 'autoUpdate',
+    devOptions: {
+      enabled: true
+    },
+    workbox: {
+      globPatterns: ['**/*.{js,css,html,ico,png,svg,jpg,jpeg,gif}']
+    },
+    manifest: {
+      name: 'vite-template-doly',
+      description: 'a vite template',
+      short_name: 'VTD',
+      display: 'standalone',
+      background_color: '#ffffff',
+      theme_color: '#ffffff',
+      icons: [
+        {
+          src: '/logo.png',
+          sizes: '100x100', // touch图标,建议提供192x192、512x512
+          type: 'image/png'
+        }
+      ]
+    }
+  })
  ],
  // ...
})

本地开发可以在浏览器开发者工具 应用-Service workers 查看。

注意: 如果要取消已注册的 Service Worker ,请查阅 Unregister Service Worker。如果只是本地开发或预览取消注册 Service Worker ,可以在浏览器开发工具-应用-Service Worker 点击 “取消注册” 即可。

使用 Tailwind CSS

参考:Install Tailwind CSS with ViteUsing with Preprocessors

如果使用 Tailwind CSS 的话,不建议再使用 less ,可以先卸载 pnpm rm less ,然后将 *.less 文件名改为 *.css

卸载 less 后,如果还要使用嵌套规则和 import ,需要安装对应的 postcss 插件。

安装 Tailwind CSS

pnpm add tailwindcss -D

npx tailwindcss init -p

postcss.config.js 配置

export default {
  plugins: {
    // ...
+   tailwindcss: {}
  }
};

tailwind.config.js 配置

/** @type {import('tailwindcss').Config} */
export default {
+ content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
  //...
}

src/index.css 添加 Tailwind 指令

+ @tailwind base;
+ @tailwind components;
+ @tailwind utilities;
// ...

本地运行构建结果

vite.config.tsbase 改为 '/',然后执行以下命令:

pnpm build        # 构建
npx vite preview  # 本地启用服务访问 dist

本地构建包含mock数据,用于演示

plugin-config#build构建独立部署的mock服务

.env.production.local 设置 API 地址

+ VITE_APP_API='http://localhost:8080'

vite.config.ts 配置构建 mock 服务

- plugins: [react(), useMock && mockDevServerPlugin()],
+ plugins: [react(), useMock && mockDevServerPlugin({ build: true })],

运行构建

pnpm build

进入 dist/mockServer 目录安装依赖,启用服务

cd dist/mockServer
pnpm install
pnpm start

然后再打开另一个终端,回到项目根目录,运行预览

cd ../..
npx vite preview

浏览器访问 http://localhost:4173/ 即可。