突然想在Vue2 老项目中使用 Vite2,毕竟 Vite2 是那么的快准狠。在这里记录一下过程中遇到的一些问题
项目环境:
Vue: 2.6.11
ElementUI (Admin)
Vue-Cli: 4.5

1. 整合 Vite2

在gayHub 上有大神做了个由 webpack 转换到 vite 的插件 (https://github.com/originjs/webpack-to-vite),致敬一下,这里就直接用吧
按照官方教程做完后会生成修改若干文件,这是修改的文件记录:
在这里插入图片描述
总结下:

  1. package.json 增加了对 vite 的运行环境插件支持
    在这里插入图片描述
    在这里插入图片描述

  2. 生成 vite 的配置文件 vite.config.js ,项目结构如下
    在这里插入图片描述
    同时会生成一个 index.html 作为启动入口,vite 不再以 public 中的 index.html 作为入口,加入了根目录文件启动的概念
    到这里基本 webpack -> vite 基本转换完成,下面说一下可能会产生的问题

2. 整合 Element UI 的问题

  1. Svg Icon 的整合
    整合 vite 会导致原有 svg 失效,需要安装一个插件支持 vite-plugin-svg-icons
npm install vite-plugin-svg-icons

然后配置 vite.config.js

// ....
import viteSvgIcons from 'vite-plugin-svg-icons'

export default defineConfig({
	//...省略其他内容
	
	plugins: [
    // 添加下面插件
    viteSvgIcons({
      iconDirs: [path.resolve(process.cwd(), 'src/icons/svg')],
      symbolId: 'icon-[dir]-[name]'
    })
  ]

})

配置 main.js

import 'vite-plugin-svg-icons/register'

import svgIcon from './components/SvgIcon/index.vue'
Vue.component('svg-icon', svgIcon)

这样就可以愉快的再次用上 SVG 了 😄

  1. Module "path" has been externalized for brower compatibility and cannot be accesed in client code
vue.runtime.esm.js:1897 
      Error: Module "path" has been externalized for browser compatibility and cannot be accessed in client code.
    at Object.get (__vite-browser-external:path?t=1634261733975:3)
    at VueComponent.resolvePath (SidebarItem.vue:90)
    at Proxy.render (SidebarItem.vue?vue&type=template&lang.js:1)
    at VueComponent.Vue2._render (vue.runtime.esm.js:3569)
    at VueComponent.updateComponent (vue.runtime.esm.js:4081)
    at Watcher2.get (vue.runtime.esm.js:4495)
    at new Watcher2 (vue.runtime.esm.js:4484)
    at mountComponent (vue.runtime.esm.js:4088)
    at VueComponent.Vue.$mount (vue.runtime.esm.js:8459)
    at init (vue.runtime.esm.js:3137)

整合 vite 后,path模块会报错,原因是 vite 源码中设定了不允许在客户端代码中访问内置模块代码(参考 issue )

import path from 'path'

解决方法:使用 path-browserify 代替 path 模块,详细内容参考 NPM解释(path-browserify
然后把上面的 path 引用代码改为下面这样即可

import path from 'path-browserify'
  1. 可能会出现的错误 The pacakage esbuild-window-64 could not be found ...
    顾名思义,直接安装该依赖包即可
npm install esbuild-window-64

完结撒花🎉仅供参考 😄

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐