Migrate existing projects to Vite

Recently refactoring an old project. The original project was packaged with Webpack4, and for a taste, we are going to add vite built features to the project.

Vite website

  1. Since the existing is a Webpack project, said to first have to add vite configuration file, for convenience, directly use a CLI toolkit – wp2vite to add vite configuration.

    // Install wp2vite dependencies (can also be installed under the current project)
    npm install -g wp2vite
    // Create the vite.config.js file
    wp2vite init
    Copy the code
  2. Re-npm install dependency

  3. Run NPM run vite-dev

Is path not included in auto-generated viet.config. js? I’ll introduce it myself

const  path = require(path);
Copy the code
  1. Restart NPM run vite-dev

    The service started successfully, but a G2 dependency was missing. Since the G2 library is relatively large, it was introduced in the form of CDN at the beginning. Blind guess is that externals is not configured.

    Vite-plugin-externals is a plugin similar to externals

    import { viteExternalsPlugin } from "vite-plugin-externals"; . viteExternalsPlugin({g2: "G2".dataSet: "DataSet".THREE: "THREE",}).Copy the code
  2. Delete node_modules and reinstall node_modules.

  3. Cannot read property ‘EventDispatcher’ of undefined

    Check stackOverflow to change OrbitControls to Orbit-Controls-ES6 package reference link

    import OrbitControls from 'orbit-controls-es6';
    
    const controls = new OrbitControls(camera, renderer.domElement);
    Copy the code
  4. The following problem is caused by the template file generated by Vite. You need to import the CDN package in the template file (index.html) generated by Vite

  5. When I opened the page, I found that the loading was abnormal

    By comparing the project built by WebPack and the project built by Vite, we found that webpack automatically introduced the packaged main.safdssfdsfdsf34.css, but Vite did not pack, only when used to load CSS, so a style was missing

    // Add to index.html
    *,
    *::before,
    *::after {
      box-sizing: border-box;
    }
    Copy the code
  6. Hot update failed after switching to Vite? @vitejs/plugin-react-refresh has been installed, but the hot update still doesn’t work. Every time you modify the file, the page will be refreshed.