重要提醒>蹦取!浙宜!項(xiàng)目是vue@2.7版本官辽,需要安裝@vitejs/plugin-vue2,2.7之前的版本安裝vite-plugin-vue2
一粟瞬、package.json修改與vite相關(guān)插件安裝同仆,index.html中加入
????????<script type="module" src="../src/main.js"></script>
```1、先加上啟動(dòng)命令
"scripts": {
? ? "dev": "vue-cli-service serve",
? ? "build": "vue-cli-service build",
? ? "deploy": "npx deploy",
? ? "vite": "vite"? ? ? ? ? ? ? ? //這個(gè)就是新增的vite啟動(dòng)命令
? },
????2裙品、安裝vite相關(guān)插件
? ? npm i?vite?vite-plugin-html??@vitejs/plugin-vue2? ?vite-plugin-require-transform ?@originjs/vite-plugin-commonjs ? ? ? ? ? ?//一共是五個(gè)插件
? ? 安裝完之后的package.json中就會(huì)多了五個(gè)插件:
? ??"vite": "^4.5.0",
? ? "vite-plugin-html": "^3.2.0",
? ? "@vitejs/plugin-vue2": "^2.2.0",```
????"vite-plugin-require-transform": "^1.0.21",
????"@originjs/vite-plugin-commonjs": "^1.0.3",
二俗批、在根目錄新建vite.config.js文件
? ? vite.config.js內(nèi)容如下:
```
import { defineConfig } from 'vite'
import createVitePlugin from '@vitejs/plugin-vue2'
import { createHtmlPlugin } from "vite-plugin-html"
import { viteCommonjs } from '@originjs/vite-plugin-commonjs'
import path from "path"
export default defineConfig({
server: {
host: '0.0.0.0',
port: 8080,
// 是否開啟 https
https: false,
proxy: {
'/pkulaw': {
target: 'http://192.168.0.217:37000', //測(cè)試環(huán)境
changeOrigin: true, //是否跨域
ws: true
},
}
},
plugins: [
requireTransform({
? ? ? fileRegex: /.js$|.vue$/
}),
createVitePlugin(),
createHtmlPlugin({
minify: true,
/**
* 在這里寫entry后,你將不需要在`index.html`內(nèi)添加 script 標(biāo)簽市怎,原有標(biāo)簽需要?jiǎng)h除
* @default src/main.ts
*/
entry: '/src/main.js',
/**
* 如果你想將 `index.html`存放在指定文件夾扶镀,可以修改它,否則不需要配置
* @default index.html
*/
template: '/public/index.html', ????//設(shè)置項(xiàng)目入口的html焰轻,開發(fā)、打包都執(zhí)行此路徑
}),
viteCommonjs({
skipPreBuild: true
}),
],
resolve: {
alias: {
"@": path.resolve("./src")
},
/** 暫時(shí)先加.vue, .js, .json */
extensions: [".vue", ".js", ".json"],
}
})
```
三昆雀、關(guān)于vite不支持require的問題(不考慮插件的情況下辱志,第一條中已通過插件解決此問題,本處只是簡(jiǎn)單提一下不使用插件的情況下手動(dòng)如何解決)
1狞膘、具體哪里用到require不支持可自行百度揩懒;
2、本項(xiàng)目中講公用組件注冊(cè)為全局組件的時(shí)候有用到require挽封,遂進(jìn)行了改造已球,改造前后的代碼以及截圖僅供參考
```//export default { //webpack版本注冊(cè)全局組件
//? install(Vue) {
//? ? ? /* 函數(shù) */
//? ? ? var requireComponent = require.context('./', true, /\.vue$/)
//? ? ? requireComponent.keys().forEach((item) => {
//? ? ? ? ? /* moduleDefault===相當(dāng)于 import PageTools from "@/components/PageTools"; */
//? ? ? ? ? var moduleDefault = requireComponent(item).default
//? ? ? ? ? //console.log(moduleDefault, 88);
//? ? ? ? ? Vue.component(moduleDefault.name, moduleDefault)
//? ? ? })
//? }
//}
//vite版本注冊(cè)全局組件
import {defineAsyncComponent } from 'vue'
export default {
? ? install(app){
? ? ? ? const components = import.meta.glob('./*/*.vue')
? ? ? ? console.log(components)
? ? ? ? for(const [key,value] of Object.entries(components)){
? ? ? ? ? ? const componentName = key.replace('./','').split('/')[0]
? ? ? ? ? ? app.component(componentName,defineAsyncComponent(value))
? ? ? ? }
? ? }
}
```