vite2+vue3+vant3 h5配置

3,857 阅读2分钟

此文章记载配置vite2时踩过的坑,做个笔记,如有侵权,请告知

vite中文文档 cn.vitejs.dev/guide/

如果英文很好的小伙伴也可以参考下英文文档 vitejs.dev/config/

vite还支持vue3 script-setup写法

写法参考尤大 github.com/vuejs/rfcs/…

挺方便的,O(∩_∩)O哈哈~

1.项目初始化搭建

npm init @vitejs/app 文件名 --template vue

也可以使用npm init @vitejs/app 文件名 ,然后会提示选择vue或者vue-ts等,自己选择模板

.env文件都和之前的方式一样,在.vue文件中只是从process.env方式换成了import.meta.env获取

2.安装路由

npm install vue-router@4 --save

创建router文件,在main.js文件中use到vue实例

VueRouter配置发生了改变,以前的*规则需要使用正则

import { createRouter, createWebHistory,createWebhashHistory } from "vue-router";

const routes = [//路由规则
    {
    path: "/:pathMatch(.*)",
    name: "Home",
    component: () => import("../layout/default.vue"),
  }
];
const router = createRouter({
  history: createWebHistory(),//根据业务切换
  routes
});
export default router;

createWebHistory代表history模式,createWebhashHistory代表hash模式

3.安装vuex

npm i vuex@next --save

跟路由文件方法一样,use在vue实例,用法和之前一样

import { createStore } from "vuex";
export default createStore({
  state: {

  },
  mutations: {

  },
  actions: {
 
  },
  modules: {}
});

4.安装axios

跟以前一样,这个就省略了

5.安装vant3

npm i vant@next -S

vant需要在main.js导入全局样式,可以使用 vite-plugin-style-import 或 vite-plugin-imp 实现按需引入。

npm i vite-plugin-imp -D 

vite.config.js

import vitePluginImp from 'vite-plugin-imp';
//需要在plugins中使用
plugins: [
	vitePluginImp({//组件按需导入
	libList: [{
		libName: 'vant',
		style(name) {
		return `vant/es/${name}/index.css`;
		}]
	     }),
	],

6.安装sass

因为vite构建时没有装sass,vite跟webpack版本不一样,不需要装sass-loader,只需要一行命令就够了

npm i sass -save

7.移动端Rem布局适配

npm install postcss-pxtorem -D

在根目录下创建postcss.config.js

根据需求自由配置

module.exports = {
  "plugins": {
    "postcss-pxtorem": {
      rootValue: 37.5, // Vant 官方根字体大小是 37.5
      propList: ['*'],
    }
  }
}

设置 rem 基准值可以自己手写或者使用插件 amfe-flexible

npm i -S amfe-flexible

装好后, 在main.js中引入 amfe-flexible

8.vite插件

vite-plugin-legacy兼容性处理插件

使用方法

vite.config.js

import legacyPlugin from 'vite-plugin-legacy';
//需要在plugins中使用
plugins: [
		legacyPlugin({// 兼容性处理插件
			targets: ['> 0.5%', 'last 2 versions', 'Firefox ESR', 'not dead'],
			// Define which polyfills your legacy bundle needs. They will be loaded
			// from the Polyfill.io server. See the "Polyfills" section for more info.
			polyfills: [
				// Empty by default
			],
			// 切换是否使用了browserslist配置源。
			// https://babeljs.io/docs/en/babel-preset-env#ignorebrowserslistconfig
			ignoreBrowserslistConfig: false,
			// When true, core-js@3 modules are inlined based on usage.
			// When false, global namespace APIs (eg: Object.entries) are loaded
			// from the Polyfill.io server.
			corejs: false
		})
	],

9.vite配置注意项

vite2别名配置进行了修改

const path = require('path');
const Resolve = name => path.resolve(__dirname, name);
export default defineConfig({
     resolve: {
		alias: [//新版别名设置 旧版key-value已过时
			{find:'@',replacement:Resolve('./src')},
			{find:'@utils',replacement:Resolve('./src/utils')}
		]
	}
  })

10.vite批量导入文件

import { Component } from 'vue'

interface FileType {
    [key: string]: Component
}

// 导入 components 下面的 所有 .vue文件
const files: Record<string, FileType> = import.meta.globEager("./components/*.vue")

export default (obj={}): typeof obj => {
    // files对象key返回的是文件路径,需要再处理一层
    Object.keys(files).forEach((c: string) => {
        const component = files[c]?.default
        let name = c.substring(c.lastIndexOf('/') + 1, c.lastIndexOf('.vue'));
        obj[name as string]=component
    })
    return obj
}

注意

  • 1.vue文件使用不了require
  • 2.运行时获取环境变量需要使用import.meta.env