目前项目使用的打包工具是 webpack,由于项目文件较多,启动开发服务器需要耗费很长的时间,非常影响效率,即使使用 HMR,文件修改后的效果也需要几秒钟才能在浏览器中反映出来。将打包工具改成 Vite 可以极大提高打包速度。使用 webpack-to-vite 可快速修改已有项目。

Vite 配置

全局安装 Vite 后可以很方便的生成 Vue 项目,不过目前项目使用的是 Vue 2.x,需要用到 vite-plugin-vue2 这个插件。

  1. npm install -g vite@latest

在根目录创建 vite.config.js 文件

  1. import { defineConfig } from 'vite';
  2. import { createVuePlugin } from 'vite-plugin-vue2';
  3. export default defineConfig({
  4. plugins: [
  5. createVuePlugin(),
  6. ],
  7. });

项目结构调整

移动 index.html 到根目录,并引入 main.js 文件:

  1. <script type="module" src="./src/main.js"></script>

Vite 文档中说明,public 中的资源不应该被 JavaScript 文件引用,此前放在 public 文件下的 js 文件改为在 index.html 中通过 script 标签引入,且 public 目录中的资源在开发时能直接通过 / 根路径访问到,所以文件路径可以直接为 /xx.js。

  1. <script src="/flexible.js"></script>

Less 变量全局导入

webpack 中使用 style-resources-loader 给所有 less 文件注入资源,需要修改:

  1. // vite.config.js
  2. {
  3. css: {
  4. preprocessorOptions: {
  5. less: {
  6. additionalData: `@import "src/styles/var.less";@import "src/styles/mixin.less";`
  7. }
  8. }
  9. }
  10. }

Vuex 修改

Vue Hot Reloading 的配置需要删除:

  1. // src/store/index.js
  2. if (module.hot) {
  3. module.hot.accept(files.id, () => {
  4. store.hotUpdate({
  5. modules,
  6. });
  7. });
  8. }

require.context

如果使用了 require.context,会报错 index.js:6 Uncaught ReferenceError: require is not defined,因为这个功能是 webpack 提供的,Vite 也提供了类似的功能 Glob导入。如果不修改源码,可以使用 @originjs/vite-plugin-require-context 插件:

  1. // vite.config.js
  2. import ViteRequireContext from '@originjs/vite-plugin-require-context';
  3. {
  4. plugins: [
  5. ViteRequireContext(),
  6. ]
  7. }

图片路径问题

样式文件中图片的引用路径由 ~@ 开头,需要将 ~ 删掉,不过也可以配置别名:

  1. // vite.config.js
  2. {
  3. resolve: {
  4. alias: [
  5. {
  6. find: '~@',
  7. replacement: path.resolve(__dirname, 'src'),
  8. },
  9. ],
  10. },
  11. }

Vue 文件引用问题

引入 vue 文件如果忽略后缀会报错: [vite] Internal server error: Failed to resolve import "./Header" from "src/Index.vue". Does the file exist?。文档中有相关说明:

不 建议忽略自定义导入类型的扩展名(例如:.vue),因为它会影响 IDE 和类型支持。

解决办法是按照文档说明,将后缀全部加上,对于已存在的项目,可以增加 .vue 文件扩展的配置:

  1. // vite.config.js
  2. {
  3. resolve: {
  4. extensions: [
  5. '.mjs',
  6. '.js',
  7. '.ts',
  8. '.jsx',
  9. '.tsx',
  10. '.json',
  11. '.vue',
  12. ]
  13. }
  14. }

其他问题解决

引用字体文件404

GET http://localhost:3000/fonts/PINGFANG%20HEAVY.TTF net::ERR_ABORTED 404 (Not Found),是因为文件名有空格,不需要加再 \,直接使用空格即可。使用 webpack 有无 \ 均可找到文件。

  1. @font-face {
  2. font-family: PingFangHeavy;
  3. src: url('../fonts/PINGFANG\ HEAVY.TTF'); // ==> src: url('../fonts/PINGFANG HEAVY.TTF');
  4. }