Vue2老項目使用vite2升級
基礎(chǔ)配置
- 安裝npm包
npm install vite -D
npm install @vue/compiler-sfc -D
npm install vite-plugin-vue2 -D
- 新建vite.config.js
import {defineConfig} from 'vite'
import {createVuePlugin} from 'vite-plugin-vue2'
import {resolve} from 'path'
function pathResolve(dir) {
return resolve(process.cwd(), '.', dir)
}
// vite.config.js
export default defineConfig({
server: {
host: '0.0.0.0',
},
plugins: [
createVuePlugin({
vueTemplateOptions: {}
}),
],
resolve: {
extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
alias: {
// vue2項目別名一般都是@,vue3中一般使用/@/, 為方便使用
'@': resolve('src')
}
}
})
- 給index.html增加main.js入口
<script type="module" src="/src/main.js"></script>
遇到的一些問題和解決方案
文件后綴省略導(dǎo)致頁面報錯404(例:vue文件引入時,webpack只需要文件名),在vite.config.js配置resolve.extensions中添加對應(yīng)后綴,vite默認(rèn)有['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']。
-
頁面打開顯示報錯
image-20210817151252577.png解決方法:修改main.js中的App.vue組件引入方式。
new Vue({
el: '#app',
router,
// 原 component template引入
components: { App },
template: '<App/>'
})
new Vue({
el: '#app',
router,
// 改為 render
render: h => h(App)
})
-
入口文件不是index.html,或者不在根目錄,導(dǎo)致資源報錯404.
vite官網(wǎng)說明:vite本質(zhì)是啟動一個基于項目目錄的靜態(tài)服務(wù)器,所以非index.html的入口文件只需要在url后跟上相應(yīng)的html路徑就行了
index.html => ip:port
start.html => ip:port/start.html
/vite/index.html => ip:port/vite/index.html
這樣開發(fā)環(huán)境就可以訪問了,然后解決打包問題,需要修改vite.config.js中的build.rollupOptions配置
// 以start.html為例
build: {
rollupOptions: {
input: process.cwd() + '/start.html'
}
}
