Once again, Vite and VUe3 have been out for a long time, but they have never been produced and practiced. Before, THEY used VUE2. Through this practice, I still prefer to use the classic and popular VUE2, maybe this is the last stubborn of many die-hards who are unwilling to follow the technology update. Vue3’s

1. Preparation for the project

  1. Familiarize yourself with vue3 documentation and Vite documentation
  2. Vsoce editor installationVue Language Features (Volar)expand

2. Some problems about Vite

The biggest feeling of Vite is “fast”, local development is much faster than Webpack, because there is no need to pack all the modules and then start, browser native support ES module, file modification will take effect, even if the modification of vite. Config. js configuration file, can also listen to, automatic restart.

2.1 About packaging into ES5 code

The build.target configuration item specifies the build target. Traditional browsers can use the @vitejs/ plugin-Legacy plugin to support the build target. It is only supported up to ES2015 (ES6) and cannot be packaged as ES5 code. The packaged code has the type=module attribute and can be called directly inside using modularity. If you know how to make ES5, please share it with us.

// vite.config.js
import { defineConfig } from "vite";
// https://github.com/vitejs/vite/tree/main/packages/plugin-legacy
import legacy from "@vitejs/plugin-legacy";

export default defineConfig({
  plugins: [
    legacy({
      targets: ["ie >= 11"].additionalLegacyPolyfills: ["regenerator-runtime/runtime"],}),],build: {
    target: "es2015"./ / the default "modules"}});Copy the code

2.2 VitecssPreprocessor, etc.

  1. CSS preprocessors such as LESS, SCSS, SASS, and Stylus are used in vite

    Vitejs. Cn/guide/featu… Install directly, without installing loader and configuration like webPack

npm install -D less
Copy the code
<style lang="less">
/* use less */
</style>
Copy the code
  1. Postcss is used in vite

    Vitejs. Cn/config / # CSS… Postcss is integrated with Vite. You do not need to install postCSS separately

  2. Autoprefixer is used in Vite

import autoprefixer from "autoprefixer";

export default defineConfig({
  css: {
    postcss: {
      plugins: [autoprefixer],
    },
  },
});
Copy the code

2.3 Vite Packaging Separates THE JS and CSS folders

After the default package, JS and CSS are all mixed together, very uncomfortable to obsessive-compulsive disorder

Github.com/vitejs/vite…

export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        chunkFileNames: "static/js/[name]-[hash].js".entryFileNames: "static/js/[name]-[hash].js".assetFileNames: "static/[ext]/[name]-[hash].[ext]",},},},});Copy the code

2.4 Vite Root Directoryvite.config.jsConfiguration file asynchronous configuration

Officially supported by default

Cn. Vitejs. Dev/config / # asy…

export default defineConfig(async ({ command, mode }) => {
  const data = await asyncFunction();
  return {
    // The unique configuration required to build the pattern
  };
});
Copy the code

2.5 Vite Root directoryvite.config.jsConfiguration file Readingenvvariable

Using import. Meta. Env. XXX directly in the configuration file is an error, but with the above asynchronous configuration, it is convenient to read env variables, we can use fs directly

  • .envfile
# PROXY_URL
VITE_PROXY_URL=http://xxxxxx/
# DBPATH_ENV
DBPATH_ENV=XXXX
Copy the code
  • vite.config.jsfile
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const fsState = promisify(fs.stat);
const readFile = promisify(fs.readFile);

// Define a function to read the contents of the. Env file
async function getEnvConfig(vite_env_key) {
  const envFilePath = path.resolve(__dirname, "./.env");
  const [notExistEnvFile, existEnvFile] = await fsState(envFilePath)
    .then((data) = > [null, data])
    .catch((e) = > [e, null]);

  if (notExistEnvFile || existEnvFile.size <= 0) return;

  const envContent = await readFile(envFilePath, "utf8");

  if(! envContent)return;

  const envContentArr = envContent
    .split("\n")
    .filter((str) = >! str.startsWith("#")) // Filter out comment lines
    .filter(Boolean);

  const resultKey = envContentArr.find((item) = > item.includes(vite_env_key));

  return resultKey ? resultKey.split("=") [1] : null;
}

const resolveConf = async() = > {// Read the value of VITE_PROXY_URL in. Env
  const PROXY_URL = await getEnvConfig("VITE_PROXY_URL");

  return {
    server: {
      host: "0.0.0.0".port: 3000.open: true.proxy: {
        "/api": {
          target: PROXY_URL,
          changeOrigin: true.// rewrite: (path) => path.replace(/^\/api/, ""),}},}}; };export default defineConfig(resolveConf());
Copy the code

2.6 vite projectindex.htmlThe use ofenvThe environment variable

How like HTML – webpack webpack project – the plugin to use % > < % = htmlWebpackPlugin. The options. The title, this way the dynamic injection variable, vite vite can be used in the plugin – HTML to complete.

  1. The installation
npm i vite-plugin-html -D
Copy the code
  1. Use (such as dynamic injection of AMAP in different environmentskey)
  • vite.config.jsThe configuration file
import { minifyHtml, injectHtml } from "vite-plugin-html";

const AMAP_KEY = "xxx";

export default defineConfig({
  plugins: [
    injectHtml({
      data: {
        title: "hello".// Amap
        injectAMapScript: ` < script SRC = "https://webapi.amap.com/maps?v=1.4.15&key=${AMAP_KEY}"></script>`,},}),],});Copy the code
  • index.htmlDynamic injection using EJS template engine
<! DOCTYPEhtml>
<html lang="en">
  <head>
    <title><%- title %></title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
    <%- injectAMapScript %>
  </body>
</html>
Copy the code

2.7 Referencing Static Resources and Public Directories

Cn. Vitejs. Dev/config / # pub…

  1. Referencing static resources

Static resources are referenced in vue files in both relative and absolute paths in template and style

<template>
  <! -- Relative path -->
  <img src="./assets/img/test.png" />
  <! -- Absolute path -->
  <img src="/src/assets/img/test.png" />
</template>

<style scoped>
#app {
  background-image: url("./assets/img/test.png");
}
</style>
Copy the code
  1. Public directory

    Cn. Vitejs. Dev/guide/asset…

  • On thepublicFiles in directories should be referenced using absolute paths, for examplepublic/icon.pngYou should use/icon.png
  • publicResources should not beJavaScriptFile reference
<img src="/logo.png" />
Copy the code

2.8 Packing the Production Environment Remove the Console and Debugger

export default defineConfig({
  build: {
    // Remove console from production environment
    terserOptions: {
      compress: {
        drop_console: true.drop_debugger: true,},},},});Copy the code

2.9 How does asynchronous import support custom ChunkName like Webpack webpackChunkName

Github.com/vitejs/vite…

// How to support custom custom chunkName like webpack, which is packaged with a custom name
const Login = () = > import("@/views/Login");
Copy the code

Unsolved, know, trouble to share

3. Some problems about VUE3

3.1 Depth selector

V3.cn.vuejs.org/api/sfc-sty…

The previous ‘>>>’ has been deprecated and now uses the :deep() pseudo-class

<style scoped>
.a :deep(.b) {
  /* ... */
}
</style>
Copy the code

3.2 vue-router4.xRoute 404 Matching

Capture all routes or 404 Not found routes

import { createRouter, createWebHistory } from "vue-router";
const Result = () = > import("@/views/Result");

const router = createRouter({
  history: createWebHistory(),
  routes: [{// Note that the 404 page matches differently than before
      path: "/:pathMatch(.*)*".component: Result,
      name: "Result",}]});export default router;
Copy the code

3.3 <script setup>Features used invant3.xcomponent

Vant – contrib. Gitee. IO/vant/v3 / # / z…

Vant components can be used directly in < Script Setup > without component registration

<template>
  <Button />
</template>

<script setup>
import { Button } from "vant";
</script>
Copy the code

3.4 About vite after startupdefineEmitsThe warning

defineEmits is a compiler macro and no longer needs to be importe

Delete the reference to defineEmits

- import { reactive, defineEmits } from 'vue';
+ import { reactive } from 'vue';// Directly use defineEmits const emit = defineEmits(['test1', 'test2']); emit('test1', 'hello1');Copy the code

3.5 vue3 andecharts5Dynamic data update error reported. Procedure

barPolar.js:63 Uncaught TypeError: Cannot read properties of undefined (reading ‘type’)

  • The error is caused by vue3 using proxy to listen for responsiveness, and the Charts instances are converted into responsive objects within vUE
  • It can be used during initializationmarkRawSpecify non-responsive
<template>
  <div ref="lineChartDomRef"></div>
</template>

<script setup>
import { markRaw, ref, onMounted } from "vue";
import * as echarts from "echarts";

const lineChartInsRef = ref();
const lineChartDomRef = ref();

onMounted(() = > {
  // markRaw is used for initialization and linechartinsref. value is updated with linechartinsref. value
  const option = {
    // ...
  };
  lineChartInsRef.value = markRaw(echarts.init(lineChartDomRef.value));
  lineChartInsRef.value.setOption(option);

  window.addEventListener("resize".() = > {
    lineChartInsRef.value.resize();
  });
});
</script>
Copy the code

3.6 Vue3. X<script setup>How to set up componentsnameThe name of the

Forum.vuejs.org/t/vue3-2-sc…

You can actually write two script tags, the following two can coexist

<script>
import { defineComponent } from "vue";

export default defineComponent({
  name: "Test"});</script>

<script setup>
// ...
</script>
Copy the code

Keep-alive in vue-Router4. x in 3.7 VUe3

[Vue Router Warn]: <router-view> can no longer be used directly inside <transition> or <keep-alive>

  • The router – view of v – slot
  • Use keep-alive on dynamic components

If I wrote this before, I would get a warning

<keep-alive>
  <RouterView />
</keep-alive>
Copy the code

According to the hint, write this:

<template>
  <router-view v-slot="{ Component }">
    <! -- Cache components named AAA and BBB -->
    <keep-alive :include="['aaa', 'bbb']">
      <component :is="Component" />
    </keep-alive>
  </router-view>
</template>
Copy the code

3.8 VUE-Router4 Monitors route changesonBeforeRouteUpdate

import { onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue-router';

onBeforeRouteUpdate((to, from, next) = > {
  if (from.name === 'MachineList') {... } next(); });Copy the code

Page 404 is updated in 3.9 Nginx Online Deployment

Modify the nginx configuration

location / { root /usr/share/nginx/dist; Index.html index.htm; Access files by default+ try_files $uri /index.html; # Prevent browser refresh after page 404
    client_max_body_size 100m;
}
Copy the code

4. Reference materials

  1. Vue3 document
  2. Vite document
  3. Vue – router4 document