Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Up to now, the whole ecological scale of vite has a certain foundation, originally wanted to directly upgrade the project used in the work from vue2 multi-page application to vue3+ts technical architecture, but after investigation, it was found that vue3 does not support Android5, really let the head balk. Fortunately, after research, we found that Vite can support the development of VUe2 project, and the development environment does not care about browser compatibility, so we started.

Vite plugins need to be used:

vite-plugin-imp ! A component library is often required in a project to configure the style files automatically imported into the component library

vite-plugin-eslint ! It is not required, but is a plug-in introduced to facilitate uniform code formatting

vite-plugin-virtual-html ! Multipage repositories require packages that can be developed in the same path as webPack while keeping the directory unchanged.

vite-plugin-vue2 ! This is a must – use plug-in, a tool for vite to package Vue2 components

Vite basis

There are many articles related to the vite principle, and I will not transfer any other explanation. You can enter the relevant keyword search on the nuggets. Here I just want to highlight a few key points that the existing Vue2 project needs to pay attention to in the transformation of vite development:

  1. Vite project development, the entire project reference external package format must be ESM, if some libraries do not export ESM format, may need to resolve first.
  2. Vite does not replace this type of variable. This is done by WebPack before.
  3. If you are developing vite and packaging Webpack, you need to pay attention to packaging as early as possible after development to avoid unexpected problems caused by inconsistent tools.

Reform steps

SRC /pages/**/*.html entry file needs to be modified to vite development, how to do? Don’t panic, follow these steps:

  • Install Vite and the four vite plug-ins mentioned earlier using YARN
  • Declare vite startup commands in package.json, e.g. Vite: “cross-env vite”
  • Add vite.config.js to the root directory of the project, configure the config of the four plug-ins, and then migrate and configure the webPack DevServer related items (such as development port /proxy interface, etc.).
  • Yarn Vite happy development

The function of this plug-in is to do some things through the Vite server middleware, which is used to copy the resource request path and do preprocessing to THE HTML file. The core is to determine whether there are tags introduced by JS in the HTML file. If not in vite development before the start of the automatic injection with HTML file path of the module of js | ts file, there is a problem is, my HTML document template is likely to be the introduction of some external SDK script statements, this makes injection failure.

In order to solve this problem, I made some changes to the plugin to determine whether the HTML file has a script tag and put a restriction on type=”module”, because normally we would write references in HTML templates that would not be introduced in ESM format. This change ensures that the template is fully compatible with Both WebPack packaging and Vite development

For environment variables such as process.env.mode, here is the modification:

import online from './online'
import test from './test'
import dev from './dev'

let ENV = ' '
try {
  ENV = process.env.WINDOW_ENV
} catch (e) {
  ENV = 'dev'
}

const config = (() = > {
  switch (ENV) {
    case 'online':
    case 'wechat_test':
      return online
    case 'test':
      return test
    case 'dev':
      return dev
    default:
      return dev
  }
})()
Copy the code

Try… catch.. Since vite is only used in development environments, variables under import.meta are no longer used in catch.

Sounds simple, isn’t it, but the third step is far from that? I’m going to post a brief configuration (the business related ones have been hidden) and write a note to explain some key configurations.

Vite configuration details

// vite.config.js
import path from 'path'
import glob from 'glob'

import { defineConfig } from 'vite'
import { createVuePlugin } from 'vite-plugin-vue2'
import vitePluginImp from 'vite-plugin-imp'
import eslintPlugin from 'vite-plugin-eslint';
import virtualHtml from './buildPlugin/vite-plugin-virtual-html'

// Constant configuration
const VITE_APP_PORT = 3000
const VITE_APP_HOST = 'localhost'
const VITE_APP_PATH = '/'
const TEMPLATE_PATH = './src/pages/**/*.html'

// Generate a multi-page entry configuration
function getHtmls() {
  const entries = {}
  glob.sync(TEMPLATE_PATH).forEach(function(entry) {
    const basename = path.basename(entry, path.extname(entry))
    entries[basename] = entry.slice(1) // Change relative path to absolute path
  })
  return entries
}

const plugins = [
    createVuePlugin(/* options */),
    virtualHtml({
        pages: getHtmls(),
        indexPage: 'index'
    }),
    vitePluginImp(
        [{
          libName: 'vant'.style(name) {
            if (/CompWithoutStyleFile/i.test(name)) {
              // This will not import any style file 
              return false
            }
            return `vant/es/${name}/style/index.js`
          }
        }
     ]),
     eslintPlugin({ include: '**/*.+(vue|js|jsx|ts|tsx)' }),
     // If the CSS is verified, there are many strange errors
 ]

export default defineConfig({
  base: VITE_APP_PATH
  plugins,
  server: {
    port: VITE_APP_PORT,
    host: VITE_APP_HOST,
    open: '/index.html'.cors: true.proxy: {
      '^/.*api/.*': {
        target: ' '.// According to your business
        changeOrigin: true.secure: false}}},resolve: {
      // Type: string[]
      / / the default: [' MJS ', 'js' and' ts', 'JSX', 'benchmark', 'json']
      // List of extension names you want to omit when importing. If the previous import statement did not include. Vue for the vue type file, add '. Vue '.
      extensions: ['.js'.'.vue'.'.json'].alias: {
        The '@': resolve('src'),
        vue$: 'vue/dist/vue.esm.js'}}})Copy the code

Follow-up work and prospects

  • Project addition introduces @vue/ composition-API to promote the development experience of class Vue3
  • Using Vite, we tried to use rollup for packaging to completely avoid Webpack configuration and to unify the judgment of the environment in the project