Vite4+Typescript+Vue3+Pinia 从零搭建(3) - vite配置

项目代码同步至码云 weiz-vue3-template

关于vite的详细配置可查看 vite官方文档,本文简单介绍vite的常用配置。

初始内容

项目初建后,vite.config.ts 的默认内容如下:

ts 复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
})

配置别名

1. 安装 @types/node

shell 复制代码
npm i @types/node -D

2. 修改 vite.config.ts

ts 复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

// 路径查找
const pathResolve = (dir: string): string => {
  return resolve(__dirname, ".", dir);
};

// 设置别名,还可以添加其他路径
const alias: Record<string, string> = {
  "@": pathResolve("src"),
  "@views": pathResolve("src/views"),
  "@store": pathResolve("src/store")
};

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias
  },
})

3. 使用

比如,修改 App.vue:

ts 复制代码
import HelloWorld from '@/components/HelloWorld.vue'

配置环境变量

1. 新建env文件

根目录下新建 .env.env.development.env.production 三个文件。
.env 文件内新增内容:

txt 复制代码
# 本地运行端口号
VITE_PORT = 8686

.env.development 文件内新增内容:

txt 复制代码
# 本地环境
VITE_USER_NODE_ENV = development

# 公共基础路径
VITE_PUBLIC_PATH = /

.env.production 文件内新增内容:

txt 复制代码
# 线上环境
VITE_USER_NODE_ENV = production

# 公共基础路径
VITE_PUBLIC_PATH = /

2. 环境变量统一处理

根目录下新建 build 文件夹,其目录下新建 index.ts,内容如下:

ts 复制代码
// 环境变量处理方法
export function wrapperEnv(envConf: Recordable): ViteEnv {
  const ret: any = {};

  for (const envName of Object.keys(envConf)) {
    let realName = envConf[envName].replace(/\\n/g, "\n");
    realName = realName === "true" ? true : realName === "false" ? false : realName;
    if (envName === "VITE_PORT") realName = Number(realName);
    ret[envName] = realName;
    if (typeof realName === "string") {
      process.env[envName] = realName;
    } else if (typeof realName === "object") {
      process.env[envName] = JSON.stringify(realName);
    }
  }
  return ret;
}

3. 环境类型定义

types\index.d.ts 文件里新增对 RecordableViteEnv 的类型定义:

ts 复制代码
type Recordable<T = any> = Record<string, T>;

interface ViteEnv {
  VITE_USER_NODE_ENV: "development" | "production";
  VITE_PUBLIC_PATH: string;
  VITE_PORT: number;
}

修改 tsconfig.json 文件,将 build 文件夹内的文件包含进去:

json 复制代码
"include": [ // 需要检测的文件
  "src/**/*.ts",
  "build/*.ts",
  "src/**/*.d.ts",
  "src/**/*.tsx",
  "src/**/*.vue",
  "mock/*.ts",
  "types/*.d.ts",
  "vite.config.ts"
],

同理,修改 tsconfig.node.json 文件:

ts 复制代码
"include": [
  "build/*.ts",
  "types/*.d.ts",
  "vite.config.ts"
]

4. 使用

修改 vite.config.ts

ts 复制代码
import { defineConfig, loadEnv, ConfigEnv, UserConfig } from "vite"
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { wrapperEnv } from './build'

// 路径查找
const pathResolve = (dir: string): string => {
  return resolve(__dirname, ".", dir);
};

// 设置别名,还可以添加其他路径
const alias: Record<string, string> = {
  "@": pathResolve("src"),
  "@views": pathResolve("src/views"),
  "@store": pathResolve("src/store")
};

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  const viteEnv = wrapperEnv(env)

  return {
    base: viteEnv.VITE_PUBLIC_PATH,
    plugins: [vue()],
    resolve: {
      alias
    },
    server: {
      host: "0.0.0.0",
      port: viteEnv.VITE_PORT,
      https: false,
      open: true,
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      proxy: {
        "^/api": {
          target: "http://192.168.1.4:8688",
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, "")
        }
      }
    },
  }
})

目录更新

当前项目目录如下:

txt 复制代码
|   .env
|   .env.development
|   .env.production
|   .gitignore
|   index.html
|   package-lock.json
|   package.json
|   README.md
|   tree.txt
|   tsconfig.json
|   tsconfig.node.json
|   vite.config.ts
|   
+---.vscode
|       extensions.json
|       
+---build
|       index.ts
|              
+---node_modules 
+---public
|       vite.svg
|       
+---src
|   |   App.vue
|   |   main.ts
|   |   style.css
|   |   vite-env.d.ts
|   |   
|   +---assets
|   |       vue.svg
|   |       
|   \---components
|           HelloWorld.vue
|           
\---types
        index.d.ts
相关推荐
VillenK4 分钟前
版本依赖问题:vite-plugin-dts@3.1.0 与 jiti 的兼容性
前端·typescript·vite
轻口味2 小时前
AI 时代全栈开发破局:TypeScript 生态实战,从入门到部署一站式通关
前端·mongodb·docker·ai·typescript·react·next.js
Czzzzlq4 小时前
【无标题】
typescript·node.js·ai编程
mobº7 小时前
Vue3 +TypeScript 项目总结
前端·javascript·typescript
用户056694948311 天前
🔥 我把 axios 接口封装,玩出了 NestJS 的感觉
typescript
索西引擎1 天前
【理论】TypeScript 函数重载:从 Vue 3 defineEmits 说起的类型安全实践
前端·typescript
漫游的渔夫1 天前
从 if-else 乱麻到状态机:前端开发者该怎么理解多 Agent 协作?
前端·人工智能·typescript
matrixmind81 天前
sindresorhustype-fest:TypeScript 工具类型集合
前端·javascript·其他·typescript
小云小白1 天前
高性能 v-html 弹窗实现:Vue3 + Element Plus 最佳实践
vue3·弹窗·v-html
guangzan2 天前
DeepSeek-Lane:在 Cursor 内使用 DeepSeek V4 模型
typescript