vite基本配置教程

👩 个人主页:不爱吃糖的程序媛
🙋‍♂️ 作者简介:前端领域新星创作者、CSDN内容合伙人,专注于前端各领域技术,成长的路上共同学习共同进步,一起加油呀!
✨系列专栏:前端面试宝典、JavaScript进阶、vue实战
📢 资料领取:前端进阶资料以及文中源码可以在🎈公众号“不爱吃糖的程序媛”领取

最近做项目要求将webpack打包方式换成vite,下面将详细讲解一下配置vite需要修改哪些文件,以及过程中踩到的奇葩坑。

vite官网文档网址:https://vitejs.cn

1.新建viteconfig.js文件

一般在vue-cli项目中会有一个vueconfig.js文件,里面会有webpack配置;
那么新建一份viteconfig.js文件,里面是vite配置。
在这里插入图片描述

//该项目的版本是node12,有时候import引入不进去,就会用const替代
import { defineConfig, loadEnv } from 'vite';
//defineConfig是一个工具函数,不用 jsdoc 注解也可以获取类型提示
//加载环境变量(loadEnv),loadEnv接收三个参数,第一个是.env后面的名字,第二个是绝对路径,第三个参数是你环境变量名的前缀,在vite中默认是VITE_。比如loadEnv(‘abc’, process.cwd(), 'ENV');

//引入vite扩展插件
const { createVuePlugin } = require('vite-plugin-vue2');
const vitePluginHtmlConfig = require('vite-plugin-html-config');
const { viteExternalsPlugin } = require('vite-plugin-externals');
import path from 'path';
import cdnConfig from './cdn.config';

const resolve = (dir) => path.resolve(__dirname, dir);

export default defineConfig(({ command, mode }) => {
  const envParams = loadEnv(mode, __dirname);//__dirname表示当前文件所处目录
  return {
    root: resolve('./src'), //  入口index.html,注意入口js应该与index.html 同一目录下(只能写到目录,不能写到具体文件)
    base: './',
    publicDir: resolve('static'),//静态资源文件夹
    resolve: {
      alias: {
        '@': resolve('src'),//作为 entries 的选项
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },

    // 反向代理
    server: {
      host: '0.0.0.0', //服务器ip地址
      port: 5566, //本地端口
      fs: {
        strict: false, //  支持引用除入口目录的文件
      },
      // open: true, // 是否自动在浏览器打开
      proxy: {
        '/szapi': {
          target: 'https://tradesz.test.api.qywgpo.com/',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/szapi/, ''),
        },
      },
    },

    plugins: [
      createVuePlugin(),
      //  打包babel编译
      vitePluginHtmlConfig(cdnConfig.getCdnConfig()), //  使用cdn,传入分支参数判断使用哪种环境的js
      viteExternalsPlugin(cdnConfig.externals), // 打包过滤被引入cdn的包
    ],
    build: {
      //打包环境移除console.log,debugger
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      //打包文件按照类型分文件夹显示
      rollupOptions: {
        input: {
          main: path.resolve(__dirname, 'src/index.html'),
        },
        output: {
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]',
        },
      },
    },
  };
});


共享配置

root

类型: string

默认: process.cwd()

项目根目录(index.html 文件所在的位置)。可以是一个绝对路径,或者一个相对于该配置文件本身的相对路径。

base

类型: string

默认: /

开发或生产环境服务的公共基础路径。合法的值包括以下几种:

绝对 URL 路径名,例如 /foo/
完整的 URL,例如 https://foo.com/
空字符串或 ./(用于开发环境)

plugins

类型: (Plugin | Plugin[])[]

需要用到的插件数组。Falsy 虚值的插件将被忽略,插件数组将被扁平化(flatten)。

publicDir

类型: string | false

默认: “public”

作为静态资源服务的文件夹。该目录中的文件在开发期间在 / 处提供,并在构建期间复制到 outDir 的根目录,并且始终按原样提供或复制而无需进行转换。该值可以是文件系统的绝对路径,也可以是相对于项目的根目录的相对路径。

将 publicDir 设定为 false 可以关闭此项功能。

resolve.alias

类型:Record<string, string> | Array<{ find: string | RegExp, replacement: string }>

将会被传递到 @rollup/plugin-alias 作为 entries 的选项。也可以是一个对象,或一个 { find, replacement } 的数组。

当使用文件系统路径的别名时,请始终使用绝对路径。相对路径的别名值会原封不动地被使用,因此无法被正常解析。

构建选项

build.rollupOptions

类型: RollupOptions

自定义底层的 Rollup 打包配置。这与从 Rollup 配置文件导出的选项相同,并将与 Vite 的内部 Rollup 选项合并。

2.新建index.html模板

这个文件是入口文件模板

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>交易平台</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta content="always" name="referrer" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0"
    />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta
      name="apple-mobile-web-app-status-bar-style"
      content="black-translucent"
    />
    <meta name="format-detection" content="telephone=no" />
    <meta name="full-screen" content="yes" />
    <meta name="x5-page-mode" content="app" />
    <meta content="yes" />
    <meta content="black" />
    <meta content="telephone=no,email=no" />
    <script src="https://pv.sohu.com/cityjson?ie=utf-8"></script>
    
  </head>
  <body>
    <noscript>
      <strong
        >We're sorry but vue3.0 doesn't work properly without JavaScript
        enabled. Please enable it to continue.</strong
      >
    </noscript>

    <div id="app-gpo-index-hide">
      <div id="app-header">
        <div class="app-header-left">
          <img
            class="app-header-left-logo"
            src="https://gpo.oss-cn-shenzhen.aliyuncs.com/gpo/sys/qywlogo.png"
            alt="交易平台"
          />
          <span class="app-header-left-span">交易平台1111111</span>
        </div>
      </div>

      <div id="app-body"></div>
      <div id="app-body-line"></div>

      <div id="spinner">
        <div class="rect1"></div>
        <div class="rect2"></div>
        <div class="rect3"></div>
        <div class="rect4"></div>
        <div class="rect5"></div>
      </div>
    </div>

    <div id="app"></div>
    <script type="module" src="./main.js"></script>
  </body>
</html>

3.修改 package.json文件

原来的vue-cli的配置

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
  },

修改后的vite配置,以及在这个文件里面还添加了些其他的vite依赖项

"scripts": {
    "serve": "vite",
    "build": "vite build",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",
  },

4.修改 cdn.config.js文件

const getCdnConfig = () => {
  const ret = {};
  ret.scripts = cdn.js.map((e) => ({ src: e }));
  ret.links = cdn.css.map((e) => ({ rel: 'stylesheet', href: e }));
  return ret;
};
module.exports = {
  getCdnConfig,
};

5.修改 router/index.js文件

项目保留了webpack和vite两种打包方式,因此进来要判断、

const Blank = () => import('@/views/Basic/Blank');
const NotAuth = () => import( '@/views/Basic/NotAuth');
const NotFound = () => import( '@/views/Basic/NotFound');
const Book = () => import('@/views/Operation/Book'); //  操作手册
const BookItem = () => import('@/views/Operation/Book/Item'); //  操作手册(用户)----详情

const isVite = () => typeof process === 'undefined' || !process.env.VUE_APP_ENV; //判断是否是vite
const routeList = [];

if (isVite()) {
  const obj = import.meta.globEager('./*.js'); //拿到所有的批量导入js文件对象,vite里面的方法
  const list = Object.entries(obj);
  list.forEach(([key, value]) => {
    if (!key.includes('index.js')) {
      routeList.push(value.default);
    }
  });
} else {
// 利用webpack的require.context,这样路由就不用一个一个引入
  const importAll = require.context('@/router', false, /\.js$/);
  importAll.keys().forEach((path) => {
    if (!path.includes('index.js')) {
      routeList.push(importAll(path).default || importAll(path));
    }
  });
}

export default new VueRouter({
  mode: 'hash',
  routes: [
    {
      path: '/',
      name: 'blank',
      component: Blank,
    },
    {
      path: '/403',
      name: '403',
      component: NotAuth,
    },
    {
      path: '*',
      name: '404',
      component: NotFound,
    },
    {
      path: '/Book',
      component: Book,
      name: '操作手册(用户)',
      children: [
        {
          path: 'Item',
          name: '操作手册(用户)----详情',
          component: BookItem,
        },
      ],
    },
    ...routeList,
  ],
});


vite的bug坑

1.控制台请求不到auth.js和config.js的资源,报错404或者502

在这里插入图片描述
解决思路:
1.先试验文件是否引入正确;
2.再比较自己写的文件与参考的项目文件哪里不一样,可以借用工具对比;实在不行,就再对着原来项目文件重新按照顺序抄一遍也行。
3.最后发现bug居然是在proxy的 '/api’这里,因为在main.js文件那里是这样引入文件的,
在proxy的 ‘/szapi’。

/**
 * 入口文件
 */
// import Vue from 'vue';
import VueBus from "vue-bus";
// import $ from 'jquery';
import "qywgpo-public/lib/static/iconfontv2/iconfont.css"; //  图标字体
import "qywgpo-public/lib/index.css"; //  公共组件公共样式

import "@/element";
import "./../theme/index.css";
import "@/assets/css/reset.css";
import "@/assets/css/base.css";
import "@/assets/css/components.css";
import App from "@/App.vue";
import router from "@/router";
import store from "@/vuex/store";
import auth from "@/api/auth";
import pathConfig from "@/api/config";
import config from "@/config";
 proxy: {
        '/szapi': {//原来是/api
          target: 'https://tradesz.test.api.qywgpo.com/',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/szapi/, ''),
        },
},

2.import.meta.globEager和import.meta.glob的坑

先上干货

1.Vite 支持使用特殊的 import.meta.glob 函数从文件系统导入多个模块:

const modules = import.meta.glob('./dir/*.js')

以上将会被转译为下面的样子:
匹配到的文件默认是懒加载的,通过动态导入实现,并会在构建时分离为独立的 chunk。

// vite 生成的代码
const modules = {
  './dir/foo.js': () => import('./dir/foo.js'),
  './dir/bar.js': () => import('./dir/bar.js')
}

2.如果你倾向于直接引入所有的模块(例如依赖于这些模块中的副作用首先被应用),你可以使用 import.meta.globEager 代替:

const modules = import.meta.globEager('./dir/*.js')

以上会被转译为下面的样子:

// vite 生成的代码
import * as __glob__0_0 from './dir/foo.js'
import * as __glob__0_1 from './dir/bar.js'
const modules = {
  './dir/foo.js': __glob__0_0,
  './dir/bar.js': __glob__0_1
}

请注意:

这只是一个 Vite 独有的功能而不是一个 Web 或 ES 标准
该 Glob 模式会被当成导入标识符:必须是相对路径(以 ./ 开头)或绝对路径(以 / 开头,相对于项目根目录解析)。
Glob 匹配是使用 fast-glob 来实现的 —— 阅读它的文档来查阅 支持的 Glob 模式。
你还需注意,glob 的导入不接受变量,你应直接传递字符串模式。

3.运行npm run serve会先进入入口页面,再进入主页面;但是运行npm run vueserve是直接进入主页面的。

在这里插入图片描述

4.启动vite运行命令,控制台不停的加载js

在这里插入图片描述

bug回溯

刚开始使用的是动态导入import.meta.glob,控制台报错,因为异步执行routeList挂出去可能会是一个空数组;
后面使用的是直接导入import.meta.globEager,可以理解为先拿到所有的导入文件,再将它挂出去,因此它能够拿到所有的路由地址。

拓展一下

require.context()方法
用法:
require.context(directory,useSubdirectories,regExp)

directory:表示检索的目录
useSubdirectories:表示是否检索子文件夹(true或false)
regExp:匹配文件的正则表达式,一般是文件名

例子: require.context(‘@/router’, false, /.js$/);

作用:
自动化批量导入文件,可以不用直接手写引入。

在这里插入图片描述

  • 18
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序媛夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值