How to Migrate a Vue 2 Project to Vite for Lightning‑Fast Development

This article walks through why Vite dramatically speeds up development, explains its architecture, and provides a step‑by‑step guide—including configuration changes, dependency installation, and common pitfalls—to successfully migrate a Vue 2 project built with Vue‑CLI to Vite.

JD Cloud Developers
JD Cloud Developers
JD Cloud Developers
How to Migrate a Vue 2 Project to Vite for Lightning‑Fast Development

1. What is Vite

Vite (pronounced /vit/) means “fast” in French. It provides a development server based on native ES modules with extremely fast hot module replacement (HMR) and a set of build commands that use Rollup to produce highly optimized static assets for production.

2. Why is it fast

Vite separates the application into dependencies and source code . Dependencies are usually stable JavaScript libraries that can be pre‑bundled with esbuild, which is written in Go and 10–100× faster than JavaScript bundlers. Source files are served as native ESM, letting the browser request and transform them on demand, which eliminates the heavy cold‑start bundling step.

3. How to migrate the old project

3.1 Clarify project structure

The original Vue 2 project uses vue‑cli. Move index.html from the public folder to the project root because Vite treats index.html as part of the source graph. Use a single entry file, e.g. main.ts:

<script type="module" src="/src/main.ts"></script>

If you encounter the error "[vite] Internal server error: URI malformed" caused by the legacy <%= BASE_URL %> syntax, replace it with a simple plugin:

res = code.replace(/<%=\s+BASE_URL\s+%>/g, baseDir);

3.2 Install dependencies

Install Vite and the Vue 2 compatibility plugin:

npm i vite vite-plugin-vue2 -S

3.3 Modify configuration files

Update package.json scripts:

"serve": "vite",
"build": "vite build"

Create vite.config.js (similar to vue.config.js) with the following content:

import { defineConfig } from 'vite';
import { createVuePlugin } from 'vite-plugin-vue2';

export default defineConfig({
  plugins: [
    createVuePlugin({
      jsx: true,
      vueTemplateOptions: {}
    })
  ],
  resolve: {
    extensions: ['.vue', '.js', '.ts', '.jsx', '.tsx', '.json'],
    alias: [{ find: '@', replacement: '/src' }]
  },
  server: {
    open: true,
    host: 'xxxx.jd.com',
    allowedHosts: ['.jd.com', '.jdwl.com', '.jd.co.th', '.jd.id'],
    port: 80,
    cors: true,
    proxy: {
      '/api': {
        target: 'https://xxx.jd.com',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '/api')
      }
    }
  }
});

3.4 Remove old webpack‑related dependencies

Either manually uninstall them or start a fresh Vite project and copy the needed code over.

3.5 Start the application

Run npm run serve. Expect initial errors; resolve them one by one as described in the next section.

4. Issue summary

4.1 Environment variables

Webpack stores variables in process.env; Vite uses import.meta.env:

import.meta.env.MODE – string – current mode. import.meta.env.BASE_URL – string – base URL defined by base option. import.meta.env.PROD – boolean – true in production. import.meta.env.DEV – boolean – true in development (opposite of PROD).

To keep old code working, you can define a shim:

export default defineConfig({
  define: {
    'process.env': {}
  }
});

4.2 Global variable

Because Vite runs in an ESM environment, some packages expect global. Add a polyfill at the top of main.ts:

// polyfills
if (typeof (window as any).global === 'undefined') {
  (window as any).global = window;
}

4.3 SCSS global variable errors

Adjust vite.config.js to prepend SCSS variables:

export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: "$ossHostVariable: 'import.meta.env.VUE_APP_OSS_HOST';"
      }
    }
  }
});

4.4 path module

Replace Node's path with a browser‑compatible version:

import path from 'path-browserify';

4.5 require statements

Install and configure vite-plugin-require-transform:

import requireTransform from 'vite-plugin-require-transform';
export default defineConfig({
  plugins: [requireTransform({})]
});

4.6 Dynamic component imports

Use Vite's import.meta.glob to load Vue components lazily:

const load = import.meta.glob('@/views/**/index.vue');
export const constantRoutes = [
  { path: '/404', component: load['404'] }
];

4.7 Split‑chunk strategy

const SPLIT_CHUNK_CONFIG = [
  { match: /[\\/]src[\\/]_?common(.*)/, output: 'chunk-common' },
  { match: /[\\/]src[\\/]_?component(.*)/, output: 'chunk-component' }
];

const rollupOptions = {
  output: {
    chunkFileNames: 'assets/js/[name]-[hash].js',
    entryFileNames: 'assets/js/[name]-[hash].js',
    assetFileNames: 'assets/static/[name]-[hash].[ext]',
    manualChunks(id) {
      for (const item of SPLIT_CHUNK_CONFIG) {
        const { match, output } = item;
        if (match.test(id)) return output;
      }
      if (id.includes('node_modules')) {
        return id.toString().split('node_modules/')[1].split('/')[0];
      }
    }
  }
};

5. Startup time

After migration, the cold‑start time drops from several minutes to a few seconds. The following screenshots illustrate the improvement:

6. Conclusion

The migration process involves clarifying the project structure, adding vite.config.js, adjusting scripts, and handling compatibility issues such as environment variables, global objects, SCSS, path, and require statements. The result is a modern frontend toolchain that reduces cold‑start time by over 99%, greatly improving developer experience.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendbuild toolsViteesbuild
JD Cloud Developers
Written by

JD Cloud Developers

JD Cloud Developers (Developer of JD Technology) is a JD Technology Group platform offering technical sharing and communication for AI, cloud computing, IoT and related developers. It publishes JD product technical information, industry content, and tech event news. Embrace technology and partner with developers to envision the future.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.