系统搭建三---------vite的一些配置

332 阅读4分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

我只是记录自己的东西,参考文章 有来 vue3element-admin: https://www.youlai.tech/pages/5d571c/#%E8%B7%AF%E5%BE%84%E5%88%AB%E5%90%8D%E9%85%8D%E7%BD%AE

1. 路径别名配置

使用 @ 代替 src

1.1 Vite配置

// vite.config.ts
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            "@": path.resolve("./src") // 相对路径别名配置,使用 @ 代替 src
        }
    }
})

import path from 'path'编译器报错:TS2307: Cannot find module 'path' or its corresponding type declarations.

本地安装 Node 的 TypeScript 类型描述文件即可解决编译器报错

npm install @types/node --save-dev

1.2 TypeScript 编译配置

同样还是import path from 'path' 编译报错: TS1259: Module '"path"' can only be default-imported using the 'allowSyntheticDefaultImports' flag

因为 typescript 特殊的 import 方式 , 需要配置允许默认导入的方式,还有路径别名的配置

// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./", // 解析非相对模块的基地址,默认是当前目录
    "paths": { //路径映射,相对于baseUrl
      "@/*": ["src/*"] 
    },
    "allowSyntheticDefaultImports": true // 允许默认导入
  }
}

2. 环境变量

官方教程: cn.vitejs.dev/guide/env-a…

2.1. env配置文件

项目根目录分别添加 开发、生产和模拟环境配置

  • 开发环境配置:.env.development

    # 变量必须以 VITE_ 为前缀才能暴露给外部读取
    VITE_APP_TITLE = 'vue3-pina-vite-elementPlus'
    VITE_APP_PORT = 3000
    VITE_APP_BASE_API = '/dev-api'
    
  • 生产环境配置:.env.production

    VITE_APP_TITLE = 'vue3-pina-vite-elementPlus'
    VITE_APP_PORT = 3000
    VITE_APP_BASE_API = '/prod-api'
    
  • 模拟生产环境配置:.env.staging

    VITE_APP_TITLE = 'vue3-pina-vite-elementPlus'
    VITE_APP_PORT = 3000
    VITE_APP_BASE_API = '/prod--api'
    

2.2 环境变量智能提示

添加环境变量类型声明

// src/ env.d.ts
// 环境变量类型声明
interface ImportMetaEnv {
  VITE_APP_TITLE: string,
  VITE_APP_PORT: string,
  VITE_APP_BASE_API: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

3. 浏览器跨域处理

3.1.跨域原理

浏览器同源策略: 协议、域名和端口都相同是同源,浏览器会限制非同源请求读取响应结果。

解决浏览器跨域限制大体分为后端和前端两个方向:

  • 后端:开启 CORS 资源共享;
  • 前端:使用反向代理欺骗浏览器误认为是同源请求;

3.2 端反向代理解决跨域

// vite.config.ts
import { UserConfig, ConfigEnv, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  // 获取 .env 环境配置文件
  // process.cwd(): 项目根目录(index.html 文件所在的位置)。可以是一个绝对路径,或者一个相对于该配置文件本身的相对路径。
  const env = loadEnv(mode, process.cwd())
  // console.log(env)
  return {
    plugins: [
      vue(),
      // name
      VueSetupExtend(),
      // 图标
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]'
      })
    ],
    // 本地反向代理解决浏览器跨域限制
    server: {
      hmr: true,
      host: 'localhost',
      port: Number(env.VITE_APP_PORT),
      open: true, // 启动后是否自动打开浏览器
      proxy: {
        [env.VITE_APP_BASE_URL]: {
          target: 'http://152.136.185.210:4000', // 自己项目地址
          changeOrigin: true, // 开启跨越
          // rewrite: (path) => path.replace(/^/api/, '') // 这样写的话需要针对不同环境配置这个请求变量,并且需要注意前面这个 ^ 要进行 \ 转义
          rewrite: (path) =>
            path.replace(new RegExp('^' + env.VITE_APP_BASE_URL), '')
        }
      }
    },
    //
    resolve: {
      alias: {
        '@': path.resolve('./src') // 相对路径别名配置,使用 @ 代替 src
      }
    }
  }
}

4.下面是我的一些基本配置(注释基本都写啦,可以看一看)

  1. VueSetupExtend vue3组件内的name无法书写的插件
  2. element-plus组件的自动按需导入,基本就是按官网来的
  3. vite-plugin-style-import 插件 是因为第二步我按需导入后 使用 ElMessage 后没有出现组件,是因为样式问题,解决
  4. vite中 bulid 生产环境时移除console.log()
import { UserConfig, ConfigEnv, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

// 图标插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
// 解决setup无法写name的插件
import VueSetupExtend from 'vite-plugin-vue-setup-extend'

// 按需导入 - 自动导入element-puls组件 官网
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// 解决 自动导入 ElMesasge 无反应,没样式,插件:yarn add vite-plugin-style-import consola -D
import {
  createStyleImportPlugin,
  ElementPlusResolve
} from 'vite-plugin-style-import'

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  // 获取 .env 环境配置文件
  // process.cwd(): 项目根目录(index.html 文件所在的位置)。可以是一个绝对路径,或者一个相对于该配置文件本身的相对路径。
  const env = loadEnv(mode, process.cwd())
  // console.log(env.VITE_APP_BASE_URL, 'env.VITE_APP_BASE_URL')

  return {
    plugins: [
      vue(),
      // name
      VueSetupExtend(),
      // 图标
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]'
      }),
      // 自动导入 element-plus 组件
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()]
      }),
      // 解决 ElMesasge 样式导入
      createStyleImportPlugin({
        resolves: [ElementPlusResolve()],
        libs: [
          {
            libraryName: 'element-plus',
            esModule: true,
            resolveStyle: (name: string) => {
              return `element-plus/theme-chalk/${name}.css`
            }
          }
        ]
      })
    ],
    // 本地反向代理解决浏览器跨域限制
    server: {
      hmr: true,
      host: 'localhost',
      port: Number(env.VITE_APP_PORT),
      open: true, // 启动后是否自动打开浏览器
      proxy: {
        [env.VITE_APP_BASE_URL]: {
          target: 'https://zyjy-dev.51jshl.com/api', // 自己项目地址
          ws: true,
          changeOrigin: true, // 开启跨越
          rewrite: (path) => path.replace(/^\/api/, '/') // 这样写的话需要针对不同环境配置这个请求变量,并且需要注意前面这个 ^ 要进行 \ 转义
          // rewrite: (path) =>
          //   path.replace(new RegExp('^' + env.VITE_APP_BASE_URL), '')
        }
      }
    },
    //
    resolve: {
      alias: {
        '@': path.resolve('./src'), // 相对路径别名配置,使用 @ 代替 src
        '~/': `${path.resolve(__dirname, 'src')}/`
      }
    },
    // 解决 自动导入 ElMesasge 无反应
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "~/style/element/index.scss" as *;`
        }
      }
    },
    // 打包
    build: {
      minify: 'terser',
      terserOptions: {
        compress: {
          //生产环境时移除console.log()
          drop_console: true,
          drop_debugger: true
        }
      }
    }
  }
}