vite搭建vue3项目及相关配置

1.npm create vite

设置你的项目名,选择框架,选择语言

我此处选的为Vue + typescripe

2.按照命令去执行 cd vite-vue3-app 进入项目文件,npm install 安装依赖,npm run dev 运行项目

此处由于node、npm版本导致报错问题如图

在安装依赖的时候有提示node版本需要大于18,而我本地的node版本为16.20.1 npm版本为8.19.4

解决方法 1.升级node版本(我用的nvm版本管理工具,切换到高版本,删除node_modules文件夹,重新安装依赖)

vue3的官方文档也要求node版本要18+,

方法2.如果由于各种原因不能升级node,那需要手动修改package.json中vite的版本,降低vite的版本到例如 4.4.5(删除node_modules文件夹,重新安装依赖,然后启动项目)

3.安装项目所需的基础插件

看你自己需要啥,安装啥,此处我安装的依赖

npm install axios pinia vue-router vant -S

Vant 是一个轻量、可定制的移动端组件库 Vant 4 - A lightweight, customizable Vue UI library for mobile web apps.

npm install less unplugin-auto-import unplugin-vue-components @vant/auto-import-resolver postcss-px-to-viewport @types/node -D

4.配置vite.config.ts

复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from '@vant/auto-import-resolver';
import postcssPxToViewport from 'postcss-px-to-viewport';
import resolveConfig from './resolveConfig/resolveConfig';
import tsConfig from './viteConfig/plugins/setTsConfig';
import path from 'path';
import replaceCode from './viteConfig/plugins/replaceCode';
// https://vite.dev/config/
export default defineConfig({
  base: './',
  server: {
    host:true
  },
  plugins: [
    vue(),
    tsConfig(),
    replaceCode([
      {
        search: '@paycenter',
        replace: '----',//你自己需要替换的域名地址等
        attr: 'ig',
      }
    ]),
    AutoImport({
      imports: ['vue', 'vue-router'],
      // 可以选择auto-import.d.ts生成的位置,使用ts建议设置为'src/auto-import.d.ts'
      dts: 'src/auto-import.d.ts',
    }),
    Components({
      resolvers: [VantResolver()],
    }),
  ],
  resolve:{
    alias: {
      '@':path.resolve(__dirname,'src'),
      ...resolveConfig,
    }
  },
  css: {
    postcss: {
      plugins: [
        postcssPxToViewport({
          unitToConvert: 'px', // 要转化的单位
          viewportWidth: 375, // UI设计稿的宽度
          // viewportHeight: 667, //视口的高度,对应的是设计稿的高度(也可以不配置)
          unitPrecision: 6, // 转换后的精度,即小数点位数
          propList: ['*'], // 指定转换的css属性的单位,*代表全部css属性的单位都进行转换
          viewportUnit: 'vw', // 指定需要转换成的视窗单位,默认vw
          fontViewportUnit: 'vw', // 指定字体需要转换成的视窗单位,默认vw
          selectorBlackList: ['ignore'], // 指定不转换为视窗单位的类名,
          minPixelValue: 1, // 默认值1,小于或等于1px则不进行转换
          mediaQuery: true, // 是否在媒体查询的css代码中也进行转换,默认false
          replace: true, // 是否转换后直接更换属性值
          exclude: [/node_modules/], // 设置忽略文件,用正则做目录名匹配
          landscape: false, // 是否处理横屏情况
        }),
      ],
    },
  },
  build: {
    outDir: process.env.NODE_ENV,
    chunkSizeWarningLimit: 1500,
    assetsDir: 'assets',
    terserOptions: {
      // 清除console和debugger
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor'
          }
        },
      },
    },
  },
})

vite.config.ts 中涉及的文件如下

replaceCode.ts

复制代码
function replaceCodePlugin(options) {
    return {
        name: "替换文件内特殊内容",
        transform(code) {
            let filterCode = code;
            options.forEach(item => {
                let reg = new RegExp(item.search, item.attr);
                filterCode = filterCode.replace(reg, item.replace);
            })
            return {
                code: filterCode,
            }
        },
    };
}
export default replaceCodePlugin

setTsConfig.ts

复制代码
import fs from 'fs';
import tsJson from '../tsconfigTemplate'
import path from 'path';
function tsConfigPlugin(){
    return {
        name:"替换tsconfig.json",
        buildStart(){
            let filePath=path.resolve(__dirname,"../../tsconfig.json");
            fs.writeFileSync(filePath,JSON.stringify(tsJson));
        }
    }
}

export default tsConfigPlugin; 

tsconfigTemplate.ts

复制代码
import resolveConfig from '../resolveConfig/resolveConfig'
let tsJson={
    "compilerOptions": {
      "types": ["vite/client","node"],
      "target": "ES2020",
      "useDefineForClassFields": true,
      "module": "ESNext",
      "lib": ["ES2020", "DOM", "DOM.Iterable"],
      "skipLibCheck": true,
  
      "moduleResolution": "bundler",
      "allowImportingTsExtensions": true,
      "resolveJsonModule": true,
      "isolatedModules": true,
      "noEmit": true,
      "jsx": "preserve",
  
      "strict": false,
      "noUnusedLocals": true,
      "noUnusedParameters": true,
      "noFallthroughCasesInSwitch": true,
      "baseUrl":"",
      "paths":{
      }
    },
    "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
    "references": [{ "path": "./tsconfig.node.json" }],
};

for(let key in resolveConfig){
  tsJson.compilerOptions.paths[key]=[resolveConfig[key]]
}

export default tsJson;

resolveConfig.ts

复制代码
import path from 'path';
const resolveConfig = {
    '@/*':"src/*",
    error: path.resolve(__dirname, '../src/pages/error/index.vue'),
    '@payment': path.resolve(__dirname, '../src/pages/payment'),
    '@payment/*': 'src/pages/payment/*'
};
export default resolveConfig;
相关推荐
Leo655356 分钟前
动态透视报表 + 查询接口 + Excel导出
开发语言·windows·python
前端Hardy11 分钟前
别再手写代码了!2026 前端 5 个 AI 杀招,直接解放 80% 重复劳动(附工具+步骤)
前端·javascript·面试
SuperEugene14 分钟前
Element Plus/VXE-Table UI 组件库规范:统一用法实战,避开样式冲突与维护混乱|工程化与协作规范篇
前端·javascript·vue.js·ui·前端框架·element plus·vxetable
前端Hardy29 分钟前
前端工程师必备的 10 个 AI 万能提示词(Prompt),复制直接用,效率再翻倍!
前端·javascript·面试
BioRunYiXue33 分钟前
Nature Methods:CellVoyager 自主 AI 智能体开启生物数据分析新时代
大数据·开发语言·前端·javascript·人工智能·数据挖掘·数据分析
网络点点滴1 小时前
Vue3中Suspense的使用
前端·javascript·vue.js
kcuwu.2 小时前
Python面向对象:封装、继承、多态
开发语言·python
一定要AK2 小时前
Java流程控制
java·开发语言·笔记
河西石头2 小时前
分享python项目与开源python项目中的效率法宝--requirements文件的使用
开发语言·python·requirements文件·批量安装python依赖·python虚拟环境配置