SoFunction
Updated on 2025-04-04

Steps to refactor the Vue Cli project into Vite

We knowVueCliUsedwebpackPackaging tools, andViteIt is based onESMpackage tool, so we can useViteLet's replaceVueCli, to improve our development experience.

Update dependencies and

We first delete the VueCli-related dependencies in the project, and then install the Vite-related dependencies.

:::tip package management tool we usepnpmIf you are usingnpmoryarn, please replace it yourself. :::

  • deleteVueCliRelated dependencies
pnpm remove @vue/cli-plugin-babel @vue/cli-plugin-eslint @vue/cli-service
  • InstallViteRelated dependencies

::: warning Note If you are usingvue2.6, please installvite-plugin-vue2, and not requiredjsxsupport :::

pnpm add -D vite @vitejs/plugin-vue @vitejs/plugin-vue2 @vitejs/plugin-vue2-jsx
  • At the same time we can removebabelRelated dependencies
pnpm remove -D babel-plugin-dynamic-import-node babel-eslint
  • Modify scripts

ReviseIn-housescripts

{
  "scripts": {
    "dev": "vite --host",
    "build:prod": "vite build",
    "build:stage": "vite build --mode staging"
  }
}

Configure Vite

  • createand add basic configuration
import { defineConfig, loadEnv } from 'vite';
// If you are using vue2.6, please use vite-plugin-vue2// import { createVuePlugin as vue } from 'vite-plugin-vue2';
import vue from '@vitejs/plugin-vue2';
import { resolve } from 'path';
import rollupNodePolyFill from 'rollup-plugin-node-polyfills';
import { dataToEsm } from '@rollup/pluginutils';
import vueJsx from '@vitejs/plugin-vue2-jsx';

export default ({ mode }) => {
   = { ..., ...loadEnv(mode, (), '') };

  return defineConfig({
    plugins: [
      // vue2.6
      // vue({ jsx: true }),
      // vue2.7
      vue(),
      vueJsx(),
    ],
    server: {
      port: 75,
      proxy: {
        [.VITE_APP_BASE_API]: {
          target: .VITE_APP_PROXY_API,
          changeOrigin: true,
          rewrite: (path) => (new RegExp(`^${.VITE_APP_BASE_API}`), ''),
        },
      },
    },
    resolve: {
      alias: {
        '@': resolve('src'),
      },
      extensions: ['.js', '.vue', '.json'],
    },
  });
};
  • If you use some modules of node in your project, you need toAdd the corresponding polyfill to

:::tip prompt Need to addrollup-plugin-node-polyfillsDependency :::

defineConfig({
  // ...
  resolve: {
    alias: {
      '@': resolve('src'),
      // If you use some node modules in your project, you need to add the corresponding polyfill here. If you do not configure the extensions of .js, you need to add .js at the end.      path: 'rollup-plugin-node-polyfills/polyfills/path',
  }
})
  • If your project needs to usebuildFor configuration, you can refer to the following configuration
defineConfig({
  // ...
  build: {
    rollupOptions: {
      output: {
        chunkFileNames: 'js/[name]-[hash].js',
        entryFileNames: 'js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash][extname]',
        // Separate dependency packages        manualChunks: {
          vue: ['vue'],
          echarts: ['echarts'],
          'element-ui': ['element-ui'],
        },
      },
    },
  },
});
  • Remove
  • If you use it in your projectjsx, please modify the '.js' file to '.jsx'

Global replacement of Env variables andrequire

  • Put allReplace with,like:
// Before replacementconst uploadFileUrl = .VUE_APP_BASE_API + '/upload';
// After replacementconst uploadFileUrl = .VITE_APP_BASE_API + '/upload';

:::tip Reference Regularprocess\.env\.VUE_APP_ replace .VITE_APP_ :::

::: danger Note: do notIn-houseReplace with :::

  • Import all directlyrequireReplace withimport,like:
// Before replacementconst { version } = require('../../');
// After replacementimport { version } from '../../';

:::tip Reference Regularconst\s+\{(.+?)\}\s+=\s+require\((.+?)\); replace import {$1} from $2; :::

  • Remove dynamically imported,like:
// Before replacementconst svgIcons = ('@/assets/icons/svg', false, /\.vue$/);
// After replacementconst svgIcons = ('@/assets/icons/svg'); 
  • The dynamically imported Vue routing components need to be adjusted toimport(),like:
// Before replacement = () => require([`@/views/${}`]);
// After replacement
// Dynamic importconst views = ('@/views/**/**.vue');
 = views[`@/views/${}.vue`];

// Determine the dynamic import of file path// Before replacement = () => require('@/views/index/index');
// After replacement = () => import('@/views/index/');

Adjust ESLint configuration

Removebabel-eslint parser

// .
 = {
  // ...
  // Remove  // parser: 'babel-eslint',
  // ...
};

Adjustment

movepublic/to, and addJavaScript modulesHow to introduce

<!-- ... -->
<script type="module" src="/src/"></script>
<!-- ... -->

:::tip prompt<script>Tags are usually added in</body>forward :::

SVG Support

  • Installation dependencies
pnpm add -D vite-plugin-svg-icons
  • Revise, the reference configuration is as follows:
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';

defineConfig({
  // ...
  plugins: [
    // ...
    createSvgIconsPlugin({
      // In the icon folder, all svg files will be converted to svg elves      iconDirs: [resolve((), 'src/assets/icons/svg')],
      // Specify the symbolId format      symbolId: 'icon-[dir]-[name]',
    }),
  ],
});
  • Add virtual modules to the entry file, such as:
// src/
// ...
import 'virtual:svg-icons-register';
// ...
  • Add toSvgIcon/Components
<template>
  <div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
  <svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName" rel="external nofollow"  />
  </svg>
</template>

<script>
import { isExternal } from '@/utils/validate';

export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true,
    },
    className: {
      type: String,
      default: '',
    },
  },
  computed: {
    isExternal() {
      return isExternal();
    },
    iconName() {
      return `#icon-${}`;
    },
    svgClass() {
      if () {
        return 'svg-icon ' + ;
      } else {
        return 'svg-icon';
      }
    },
    styleExternalIcon() {
      return {
        mask: `url(${}) no-repeat 50% 50%`,
        '-webkit-mask': `url(${}) no-repeat 50% 50%`,
      };
    },
  },
};
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>

Summarize

So far, we have completedvue-cliProject migration, we can usevitevarious advantages.

If you encounter a situation where the build product cannot be used normally, please import it in your dynamic route

refer to

  • Vite
  • Webpack to Vite

This is the article about the methods and steps of refactoring Vue Cli projects to Vite. For more related content to refactoring Vue Cli projects to Vite, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!