【Vue】Vite of Family Barrel

overview

Vite, a development server based on browser-native ES imports. Use the browser to parse imports, compile and return on-demand on the server side, completely skipping the concept of packaging, and the server can be used anytime. At the same time, it not only has Vue file support, but also handles hot update, and the speed of hot update will not slow down with the increase of modules. For the production environment, the same code can be packaged with rollup.

Vite is a new front-end building tool that can significantly improve the front-end development experience. It mainly consists of two parts:

  • A development server that provides rich built-in functions based on native ES modules, such as module hot update (HMR);
  • A set of build instructions to package your code with Rollup, and it comes pre-configured to output optimized static assets for production.

Its characteristics are:

  • Extremely fast service startup: use native ESM files, no packaging required!
  • Lightweight and Fast Hot Reload: Always extremely fast Module Hot Reload (HMR) regardless of application size
  • Rich features: support for TypeScript, JSX, CSS, etc. out of the box.
  • Optimized Builds: Pre-configured Rollup builds with optional Multi-Page App or Library modes
  • Common plugins: share the Rollup-superset plugin interface between development and build.
  • Fully Typed API: Flexible API and full TypeScript typing.

build project

Vite requires Node.js version 14.18+, 16+. However, some templates require a higher version of Node to run properly. When your package manager warns you, please upgrade your version of Node.

Using NPM:

$ npm create vite@latest

Using Yarn:

$ yarn create vite

Using PNPM:

$ pnpm create vite
然后按照提示操作即可!

You can also directly specify the project name and the template you want to use via additional command line options. For example, to build a Vite + Vue project, run:

# npm 6.x
npm create vite@latest my-vue-app --template vue

# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue

# yarn
yarn create vite my-vue-app --template vue

# pnpm
pnpm create vite my-vue-app --template vue

Vite configuration items

alias

configure proxy

environment variable

project configuration

preprocess style

Install less/sass directly and use it without any configuration.

$ yarn add less -D
$ yarn add sass -D

Mobile Adaptation Solution

Installation dependencies:

$ yarn add postcss-pxtorem autoprefixer -D

Create a postcss.config.js file in the root directory:

module.exports = {
    
    
  plugins: {
    
    
    autoprefixer: {
    
    
      overrideBrowserslist: [
        "Android 4.1",
        "iOS 7.1",
        "Chrome > 31",
        "ff > 31",
        "ie >= 8",
      ],
    },
    "postcss-pxtorem": {
    
    
      rootValue: 37.5, // Vant 官方根字体大小是 37.5
      propList: ["*"],
      selectorBlackList: [".norem"], // 过滤掉.norem-开头的class,不进行rem转换
    },
  },
};

Create a new src/utils/rem.ts file:

// rem等比适配配置文件
// 基准大小,注意此值要与 postcss.config.js 文件中的 rootValue保持一致
const baseSize = 37.5;
// 设置 rem 函数
function setRem() {
    
    
  // 当前页面宽度相对于375宽的缩放比例,可根据自己需要修改,一般设计稿都是宽750(图方便可以拿到设计图后改过来)。
  const scale = document.documentElement.clientWidth / 375; // 设置页面根节点字体大小(“Math.min(scale, 2)” 指最高放大比例为2,可根据实际业务需求调整)
  document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + "px";
}
// 初始化
setRem();
// 改变窗口大小时重新设置 rem
window.onresize = function () {
    
    
  setRem();
};

Import in mian.ts(x)

import "./utils/rem"

Tip: If you are prompted "Cannot compile "rem.ts" under "--isolatedModules" because it is considered a global script file. Please add import, export, or empty "export {}" statements to make it a module" at this time You should set the isolatedModules field to false in the tsconfig.json file.

Global TS type declaration

Create a typings/index.d.ts file in the root directory

export {
    
    };

// => 全局类型声明
declare global {
    
    
  interface Window {
    
    
    _hmt: any;
    wx: any;
    AlipayJSBridge: any;
  }
  namespace GD {
    
    
    interface BaseResponse<T = any> {
    
    
      code: number;
      data: T;
      msg: string;
      page: {
    
    
        pageNo: number;
        pageSize: number;
        pages: number;
        total: number;
      };
    }
  }
}

Tip: You need to add [**/*.d.ts] to the include field in the tsconfig.json file.

Then it can be accessed globally, such as:

const response = GD.BaseResponse<{
    
    name: string}>

mock.js

①. Installation dependencies:

$ yarn add mockjs -S
$ yarn add vite-plugin-mock -D

②. Introduce the plug-in vite.config.js:

import {
    
     viteMockServe } from 'vite-plugin-mock';
export default defineConfig({
    
    
  plugins: [
    viteMockServe({
    
    })
  ],
});

③. Create a new mock/test.ts file

export default [
  {
    
    
    url: "/api-dev/users",
    method: "get",
    response: (req) => {
    
    
      return {
    
    
        code: 0,
        data: {
    
    
          name: "Li-HONGYAO",
          phone: "173 **** 8669",
          address: "成都市高新区雅和南四路216号",
        },
        msg: "success",
      };
    },
  },
];

④. Simulation request

fetch("/api-dev/users")
  .then((res) => res.json())
  .then((users) => {
    
    
    console.log(users);
  });

Dynamically load static resources

When using webpack to dynamically introduce static resources, you can use the require form, but it is not advisable in vite, and an error of require is not defined will be thrown.
However, we can import it in the form of import.meta.url, which is a native function of ESM and will expose the URL of the current module. Combining it with the original URL constructor, in a JavaScript module, we can get a fully parsed static resource URL through a relative path, and its syntax is as follows:

new URL(url, import.meta.url)

Example usage:

const imgs = [
  {
    
     imgUrl: new URL('./assets/logo_1.png', import.meta.url), text: "标题1" },
  {
    
     imgUrl: new URL('./assets/logo_2.png', import.meta.url), text: "标题2" },
];

It is worth noting that the error "URL is not defined xxx" will be thrown in the production environment. At this time, we need to use a plugin: rollup-plugin-import-meta-url-to-module.

The way to use is relatively simple, first install the dependencies:

$ yarn add rollup-plugin-import-meta-url-to-module

Then configure plugins in "vit.config.js":

import urlToModule from 'rollup-plugin-import-meta-url-to-module';

export default {
    
    
  plugins: [
    urlToModule()
  ]
};

vue configuration

routing configuration

Installation dependencies:

$ yarn add vue-router@next

Create a new router directory under src, and create a new index.ts file

import {
    
     createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    
    
    path: "/",
    redirect: "/login",
  },
  {
    
    
    path: "/login",
    name: "login",
    component: () => import("pages/Login/Login.vue"),
    meta: {
    
    
      title: "登录",
    },
  },
  {
    
    
    path: "/index-page",
    name: "indexPage",
    component: () => import("pages/IndexPage/IndexPage.vue"),
    meta: {
    
    
      title: "首页",
    },
  },
];

const router = createRouter({
    
    
  history: createWebHistory(),
  routes,
});

// 导航守卫
router.beforeEach((to, from, next) => {
    
    
  if (to.path !== "/favicon.icon") {
    
    
    document.title = to.meta.title ? (to.meta.title as string) : "";
    next();
  }
});

export default router;

Mount the route in main.ts

import App from "./App.vue";
import router from "./router";

// App配置/挂载相关
// 1. 创建App
const app = createApp(App);
// 2. 注入
app.use(router);
// 3. 挂载
app.mount("#app");

state management

Installation dependencies:

$ yarn add vuex@next

Configuration: Create a store directory under src and create index.ts under store

import {
    
     InjectionKey } from "vue";
import {
    
     createStore, ActionTree, GetterTree, MutationTree, Store } from "vuex";

// 1. 声明Store类型
declare interface StoreProps {
    
    
  authUrlForIos?: string;
}
// 2. 定义注入类型
export const globalStoreKey: InjectionKey<Store<StoreProps>> = Symbol();

// 3. ---- state
const state: StoreProps = {
    
    
  authUrlForIos: "",
};
// 3. ---- getters
const getters: GetterTree<StoreProps, any> = {
    
    
  authUrlForIos: (state) => state.authUrlForIos,
};
// 3. ---- mutations
const mutations: MutationTree<StoreProps> = {
    
    
  updateAuthUrlForIos(state, payload) {
    
    
    state.authUrlForIos = payload;
  },
};
// 3. ---- actions
const actions: ActionTree<StoreProps, any> = {
    
    
  updateAuthUrlForIos({
    
     commit }, payload) {
    
    
    commit("updateAuthUrlForIos", payload);
  },
};

// 4. 创建导出
export default createStore<StoreProps>({
    
    
  state,
  getters,
  mutations,
  actions,
});

Mount: Mount the data center in main.ts

import App from "./App.vue";
import router from "./router";
import store, {
    
     globalStoreKey } from "./store";

// App配置/挂载相关
// 1. 创建App
const app = createApp(App);
// 2. 注入
app.use(router).use(store, globalStoreKey).use(vant);
// 3. 挂载
app.mount("#app");

Secondary Directory Deployment

In the case of deploying multiple projects under the same domain name, we need to configure the use of secondary directories.

Solution 1:
Set the -base option when packaging:

"build": "vue-tsc --noEmit && vite build --mode production --base=/二级目录名/",

Then configure it in router/index.ts as follows:

const router = createRouter({
    
    
  // 部署二级目录:createWebHistory(base?: string)
  history: createWebHistory("/二级目录名/"),
  routes,
});

Solution 2:
Add base configuration in the vite.config.js configuration item, such as:

base:"/YOUR_PROJECT_NAME/"

Then configure it in router/index.ts as follows:

const router = createRouter({
    
    
  // 部署二级目录:createWebHistory(base?: string)
  history: createWebHistory("/二级目录名/"),
  routes,
});

source

Vite User Guide
Vite Official Chinese Documentation

Supongo que te gusta

Origin blog.csdn.net/weixin_44231544/article/details/132297250
Recomendado
Clasificación