Vue2老項目使用vite2升級

Vue2老項目使用vite2升級

基礎(chǔ)配置

  1. 安裝npm包
npm install vite -D
npm install @vue/compiler-sfc -D
npm install vite-plugin-vue2 -D
  1. 新建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')
    }
  }
})
  1. 給index.html增加main.js入口
<script type="module" src="/src/main.js"></script>

遇到的一些問題和解決方案

  1. 文件后綴省略導(dǎo)致頁面報錯404(例:vue文件引入時,webpack只需要文件名),在vite.config.js配置resolve.extensions中添加對應(yīng)后綴,vite默認(rèn)有['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']。

  2. 頁面打開顯示報錯


    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)
})
  1. 入口文件不是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'
  }
}

已發(fā)掘金:https://juejin.cn/post/6997310696845213704

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容