Old Vue2 projects are upgraded using VITe2

Basic configuration

  1. Install the NPM package
npm install vite -D
npm install @vue/compiler-sfc -D
npm install vite-plugin-vue2 -D
Copy the code
  1. New vite. Config. Js
import {defineConfig} from 'vite' import {createVuePlugin} from 'vite-plugin-vue2' import {resolve} from 'path' function  pathResolve(dir) { return resolve(process.cwd(), '.', dir) } // vite.config.js export default defineConfig({ server: {host: '0.0.0.0',}, plugins: [createVuePlugin({vueTemplateOptions: {}}),], resolve: {extensions: [' vue ', 'MJS', 'js' and' ts', 'JSX', 'benchmark', 'json'], alias: {/ / alias is generally @ vue2 project, are generally used vue3 / @ /, for the convenience of using the '@' : resolve('src') } } })Copy the code
  1. Add main.js entry to index.html
<script type="module" src="/src/main.js"></script>
Copy the code

Some problems encountered and solutions

  1. Error 404 due to file suffix omitted (example: When importing vue files, webpack only needs the filename), add the suffix to the viet.config.js config resolve.extensions, Vite default has [‘ MJS ‘, ‘js’,’ ts’, ‘JSX’, ‘benchmark’, ‘json’].

  2. The page displays an error

Solution: Modify the app. vue component import mode in main.js. New Vue({el: '#app', router, // Original Component template introduces components: {app}, template: '< App / >'}) ` ` ` ` ` ` new Vue ({el: '# App', the router, / / to render render: h = > h (App)}) ` ` `Copy the code
  1. The entry file is not index. HTML or is not in the root directory, causing resource error 404.

    Vite essentially starts a static server based on the project directory, so entry files that are not index. HTML only need to follow the corresponding HTML path after the URL

    index.html => ip:port
    start.html => ip:port/start.html
    /vite/index.html => ip:port/vite/index.html
    Copy the code

    This way the development environment can be accessed, and then the packaging problem needs to be solved by modifying the build.rollupoptions configuration in viet.config.js

    Build: {rollupOptions: {input: process.cwd() + '/start. HTML '}}Copy the code
  2. Eventbus compatible. Since VUe3 abandoned on, ON,on,off,$emit and other methods needed in EventBus, vue2 project upgrade needs to customize eventBus function, and mitt plug-in can be used for new project development.

Class EventBus {constructor() {this.busList = {}} // Subscribe to $on(name, constructor) fn) { this.busList[name] = this.busList[name] || []; this.busList[name].push(fn); } // emit $emit(name, data) {if (this.busList[name]) {this.busList[name]. ForEach ((fn) => {fn(data); }); $off(name) {if (this.busList[name]) {delete this.buslist [name]; } } } export default new EventBus()Copy the code