1、安装pnpm
npm install pnpm -g
2、开始创建vite项目
pnpm create vite
按照步骤创建项目名称、选择框架
cd vue3-vite-project
vue-router
pnpm install vue-router@4
vuex
pnpm add vuex@next
安装UI库naive-ui
pnpm add naive-ui
Naive UI
安装axios
pnpm add axios
安装 mock 工具
pnpm add mockjs pnpm add vite-plugin-mock -D
?
安装自定义组件自动导入
pnpm install unplugin-vue-components -D
Vite配置
// vite.config.js
import { defineConfig } from 'vite'
import Components from 'unplugin-vue-components/vite'
import {
ElementPlusResolver,
AntDesignVueResolver,
VantResolver,
HeadlessUiResolver,
ElementUiResolver,
NaiveUiResolver
} from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
Components({
// ui库解析器,也可以自定义
resolvers: [
ElementPlusResolver(),
AntDesignVueResolver(),
VantResolver(),
HeadlessUiResolver(),
ElementUiResolver(),
? NaiveUiResolver()
? ]
? })
]
})
安装 unplugin-auto-import
?pnpm i -D unplugin-auto-import
自动导入vue3的hooks,借助unplugin-auto-import/vite这个插件
支持vue , vue-router , vue-i18n , @vueuse/head , @vueuse/core 等自动引入
先看效果图
// 引入前
import { ref, computed } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
//引入后
const count = ref(0)
const doubled = computed(() => count.value * 2)
// 引入前
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <div>{ count }</div>
}
//引入后
export function Counter() {
const [count, setCount] = useState(0)
return <div>{ count }</div>
}
安装 vite-auto-import-resolvers
pnpm i vite-auto-import-resolvers unplugin-auto-import -D
unplugin-auto-import 的 vite resolvers ,主要处理 vite 项目本身的 api 按需自动引入。
按需自动引入指定目录下模块的 api 。
配置插件
// vite.config.js
// 或者 vite.config.ts
import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import AutoImports from 'unplugin-auto-import/vite'
import { dirResolver, DirResolverHelper } from 'vite-auto-import-resolvers'
export default defineConfig({
plugins: [
Vue(),
// 该辅助插件也是必需的 👇
DirResolverHelper(),
AutoImports({
imports: ['vue'],
resolvers: [
dirResolver()
]
})
]
})
配置index.ts
import type { Plugin } from 'vite';
import Components from 'unplugin-vue-components/vite';
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import AutoImport from 'unplugin-auto-import/vite';
import { dirResolver, AutoGenerateImports } from 'vite-auto-import-resolvers';
import { configHtmlPlugin } from './html';
import { configMockPlugin } from './mock';
import { configCompressPlugin } from './compress';
export function createVitePlugins(viteEnv: ViteEnv, isBuild: boolean, prodMock) {
const { VITE_USE_MOCK, VITE_BUILD_COMPRESS, VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE } = viteEnv;
const vitePlugins: (Plugin | Plugin[])[] = [
// have to
vue(),
// have to
vueJsx(),
AutoImport({
// imports: ['vue', 'vue-router', 'vue-i18n', '@vueuse/head'],
imports: AutoGenerateImports(), // 自动管理,只有对应的包有装时才会自动按需设置预设
// 可以选择auto-import.d.ts生成的位置,使用ts建议设置为'src/auto-import.d.ts'
// dts: 'src/auto-import.d.ts'
resolvers: [
// dirResolver({ prefix: 'use' }), // 强制前缀为 use
dirResolver(),
],
}),
// 按需引入NaiveUi且自动创建组件声明
Components({
// dts: true,
resolvers: [NaiveUiResolver()],
// 指定组件位置,默认是src/components
dirs: ['src/components'],
// ui库解析器
// resolvers: [ElementPlusResolver()],
extensions: ['vue'],
// 配置文件生成位置
dts: 'src/components.d.ts',
}),
];
// vite-plugin-html
vitePlugins.push(configHtmlPlugin(viteEnv, isBuild));
// vite-plugin-mock
VITE_USE_MOCK && vitePlugins.push(configMockPlugin(isBuild, prodMock));
if (isBuild) {
// rollup-plugin-gzip
vitePlugins.push(
configCompressPlugin(VITE_BUILD_COMPRESS, VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE)
);
}
return vitePlugins;
}
?vite.config.ts
import type { UserConfig, ConfigEnv } from 'vite';
import { loadEnv } from 'vite';
import { resolve } from 'path';
import { wrapperEnv } from './build/utils';
// vite plugin插件配置
import { createVitePlugins } from './build/vite/plugin';
import { OUTPUT_DIR } from './build/constant';
import { createProxy } from './build/vite/proxy';
import pkg from './package.json';
import { format } from 'date-fns';
const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
pkg: { dependencies, devDependencies, name, version },
lastBuildTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
};
function pathResolve(dir: string) {
return resolve(process.cwd(), '.', dir);
}
export default ({ command, mode }: ConfigEnv): UserConfig => {
const root = process.cwd();
const env = loadEnv(mode, root);
const viteEnv = wrapperEnv(env);
const { VITE_PUBLIC_PATH, VITE_DROP_CONSOLE, VITE_PORT, VITE_GLOB_PROD_MOCK, VITE_PROXY } =
viteEnv;
const prodMock = VITE_GLOB_PROD_MOCK;
const isBuild = command === 'build';
return {
base: VITE_PUBLIC_PATH,
esbuild: {},
resolve: {
alias: [
{
find: /\/#\//,
replacement: pathResolve('types') + '/',
},
{
find: '@',
replacement: pathResolve('src') + '/',
},
],
dedupe: ['vue'],
},
plugins: createVitePlugins(viteEnv, isBuild, prodMock),
define: {
__APP_INFO__: JSON.stringify(__APP_INFO__),
},
css: {
preprocessorOptions: {
less: {
modifyVars: {},
javascriptEnabled: true,
additionalData: `@import "src/styles/var.less";`,
},
},
},
server: {
host: true,
port: VITE_PORT,
proxy: createProxy(VITE_PROXY),
// proxy: {
// '/api': {
// target: '',
// changeOrigin: true,
// rewrite: (path) => path.replace(/^\/api/, '/api/v1')
// }
// }
},
optimizeDeps: {
include: [],
exclude: ['vue-demi'],
},
build: {
target: 'es2015',
outDir: OUTPUT_DIR,
terserOptions: {
compress: {
keep_infinity: true,
drop_console: VITE_DROP_CONSOLE,
},
},
brotliSize: false,
chunkSizeWarningLimit: 2000,
},
};
};
5分钟搭建 vite + vue3 工程,简单,实用! (qq.com)
尤大推荐的神器unplugin-vue-components,解放双手!以后再也不用呆呆的手动引入(组件,ui(Element-ui)库,vue hooks等) - 掘金tov-template: vite + vue3 + ts 开箱即用现代开发模板 (gitee.com)
vue3-vite-app: 基于vite的vue3移动/PC端脚手架
|