Vite 开发快速入门

838 阅读9分钟

一、Vite简介

Vite (法语意为 "快速的",发音 /vit/) 是一种面向现代浏览器的一个更轻、更快的前端构建工具,能够显著提升前端的开发体验。除了Vite外,前端著名的构建工具还有Webpack和Gulp。目前,Vite已经发布了Vite2,Vite全新的插件架构、丝滑的开发体验,可以和Vue3的完美结合。

1.1 Vite组成

Vite构建工具由两部分组成:

  • 一个开发服务器,它基于原生 ES 模块提供了丰富的内建功能,如模块热更新(HMR)。
  • 一套构建指令,它使用 Rollup 打包你的代码,并且它是预配置的,可以输出用于生产环境的优化过的静态资源。

总的来说,Vite希望提供开箱即用的配置,同时它的插件API和JavaScript API带来了高度的可扩展性。不过,相比Vue-cli配置来说,Vite构建的项目还是有很多的配置需要开发者自己进行处理。

1.2 浏览器支持

  • 开发环境中:Vite需要在支持原生 ES 模块动态导入的浏览器中使用。
  • 生产环境中:默认支持的浏览器需要支持 通过脚本标签来引入原生 ES 模块 。可以通过官方插件 @vitejs/plugin-legacy 支持旧浏览器。

二、环境搭建

2.1 创建项目

根据Vite官网介绍,我们可以使用npm或yarn来初始化Vite项目,并且Node.js的版本需要 >= 12.0.0。使用 NPM方式

npm init vite@latest 项目名

使用 Yarn方式

yarn create vite 项目名

除此之外,还可以通过附加的命令行选项直接指定项目名称和模板。例如,要构建一个 Vite + Vue 项目,命令如下:

# npm 6.x
npm init @vitejs/app my-vue-app --template vue

# npm 7+, 需要额外的双横线:
npm init @vitejs/app my-vue-app -- --template vue

# yarn
yarn create @vitejs/app my-vue-app --template vue

输入完命令之后,按照提示操作即可。如果项目需要支持TypeScript,可以在初始化项目的时候选择vue-ts。项目创建好之后,可以发现Vite所创建好的项目其实与使用Vue-cli所创建的项目目录结构其实是差不多的。

2.2 集成Vue-Router

2.2.1 安装配置Vue-Router

Vue-Router作为大多数项目必不可少的路由工具,已经被大多数的前端项目所使用,Vue-Router可以让构建单页面应用变得更加的容易。首先,在项目中安装Vue-Router,安装命令如下:

//npm
npm install vue-router@next --save

//yarn
yarn add vue-router@next --save

安装完成之后,在src目录下创建一个文件夹router/index.ts,然后添加如下一些配置:

import { createRouter, createWebHashHistory } from 'vue-router';

const router = createRouter({
  historycreateWebHashHistory(),
  routes: [
    { path'/'component() => import('views/home.vue') }
  ]
});

export default router

然后,我们在main.ts文件中引入Vue-Router,如下所示。

import router from './router';
createApp(App).use(router).mount("#app");

2.2.2 新增路由页面

为了方便掩饰,我们再新增两个路由页面。熟悉,创建pages文件夹,把需要展示的页面创建完成。然后,我们在router/index.ts注册我们新增的页面,如下所示。

routes: [
        {
            path: "/home",
            name: "Home",
            alias: "/",
            component: () => import("../pages/Home.vue")
        },
    ]

接下来,我们再修改一下App.vue的代码,如下所示。

<template>
  <router-link to="/home">Home</router-link>
  <router-link to="/about">About</router-link>
  <router-view></router-view>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name'App'
})
</script>

接下来启动服务,就可以看到所配置的页面了,并且点击还能够跳转到对应的页面。

2.3 集成Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension (opens new window),提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。使用Vuex之前,需要先安装Vuex插件,如下所示。

//npm
npm install vuex@next --save

//yarn
yarn add vuex@next --save

安装完成之后,需要先初始化Vuex。首先,创建一个store/index.ts文件,添加如下代码。

import { createStore } from "vuex";

const store createStore({
  modules: {
    home: {
      namespacedtrue,
      state: {
        count1
      },
      mutations: {
        add(state){
          state.count++;
        }
      }
    }
  }
})

export default store;

上面的代码作用就是实现一个简单的自加功能。然后,我们在main.js文件中引入Vuex。

import { createApp } from 'vue';
import App from './App.vue';

import store from "./store";

const app = createApp(App);
app.use(store);
app.mount('#app');

完成上述操作之后,接下来我们给Vuex编写一个测试代码看Vuex是否有效。修改Home.vue的代码如下。

<template>
  <h1>Home Page</h1>
  <h2>{{count}}</h2>
  <button @click="handleClick">click</button>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';
import { useStore } from 'vuex';

export default defineComponent({
  setup () {
    const store = useStore();
    const count = computed(() => store.state.home.count);
    const handleClick = () => {
      store.commit('home/add');
    };
    return {
      handleClick,
      count
    };
  }
})
</script>

上面的代码实现的就是一个简单的自加功能,和默认示例工程的效果事一样的,只不过我们使用Vuex。

2.4 集成Eslint

ESLint是一个用来识别 ECMAScript语法, 并且按照规则给出报告的代码检测工具,使用它可以避免低级错误和统一代码的风格。集成Eslint需要安装如下一些插件:npm方式

npm install eslint -D
npm install eslint-plugin-vue -D
npm install @vue/eslint-config-typescript -D
npm install @typescript-eslint/parser -D
npm install @typescript-eslint/eslint-plugin -D
npm install typescript -D
npm install prettier -D
npm install eslint-plugin-prettier -D
npm install @vue/eslint-config-prettier -D

yarn方式

yarn add eslint --dev
yarn add eslint-plugin-vue --dev
yarn add @vue/eslint-config-typescript --dev
yarn add @typescript-eslint/parser --dev
yarn add @typescript-eslint/eslint-plugin --dev
yarn add typescript --dev
yarn add prettier --dev
yarn add eslint-plugin-prettier --dev
yarn add @vue/eslint-config-prettier --dev

安装完成之后,还需要根目录下创建一个.eslintrc文件,如下。

{
  "root": true,
  "env": {
    "browser": true,
    "node": true,
    "es2021": true
  },
  "extends": [
    "plugin:vue/vue3-recommended",
    "eslint:recommended",
    "@vue/typescript/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": 2021
  }
}

添加了配置规则之后,还需要在package.json文件的scripts中添加如下命令:

{
    "lint": "eslint --ext src/**/*.{ts,vue} --no-error-on-unmatched-pattern"
}

接下来运行一下yarn lint就可以了,可以通过eslint完成格式的校验了。不过,我们在执行yarn lint的时候会把所有的文件全部都校验一次,如果有很多文件的话,那么校验起来速度将会很慢,此时,我们一般只在git提交的时候才对修改的文件进行eslint校验,那么我们可以这么做。
那就需要使用 lint-staged插件。

//npm
npm install lint-staged -D
//yarn 
yarn add lint-staged --dev

然后,我们对package.json进行修改:

{
  "gitHooks": {
    "commit-msg": "node scripts/commitMessage.js",
    "pre-commit": "lint-staged"
  },
  "lint-staged": {
    "*.{ts,vue}": "eslint --fix"
  },
  "scripts": {
    "test:unit": "jest",
    "test:e2e": "cypress open",
    "test": "yarn test:unit && npx cypress run",
    "lint": "npx prettier -w -u . && eslint --ext .ts,.vue src/** --no-error-on-unmatched-pattern",
    "bea": "npx prettier -w -u ."   
  },
}

2.5 配置alias

在过去使用vue-cli的时候,我们总是使用@去引入某些文件,由于Vite没有提供类似的配置,所以我们需要手动的对其进行相关配置,才能继续使用@符号去快捷的引入文件。首先,我们需要修改vite.config.ts的配置。

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { join } from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [
      {
        find'@',
        replacement'/src',
      },
      { find'views', replacement'/src/views' },
      { find'components', replacement'/src/components' },
    ]
  }
});

然后,我们在修改tsconfig.json文件,如下。

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
   
   //以下为需要添加内容
    "types": ["vite/client", "jest"],
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    } 
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
  ]
}

2.6 集成element-plus

Element Plus是由饿了么大前端团队开源出品的一套为开发者、设计师和产品经理准备的基于 Vue 3.0 的组件库,可以帮助开发者快速的开发网站,如果你使用过element-ui,那么可以快速的过渡到element-plus。除了element-plus,支持Vue 3.0 的UI框架还有很多。

首先,在项目的根目录下安装element-plus,命令如下:

npm install element-plus --save

2.6.1 引入element-plus

我们可以引入整个 element-plus,也可以根据需要仅引入部分组件。如果是全部引入,只需要在main.js 添加如下代码即可。

import { createApp } from 'vue'
import ElementPlus from 'element-plus';
i

const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')

如果为了减小项目的包体积,那么只需要引入对应的功能组件即可。首先,安装 babel-plugin-component插件,如下所示。

npm install babel-plugin-component --save

然后,修改.babelrc的配置内容。

{
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-plus",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

如果我们只需要引入部分组件,比如 Button 和 Select组件,那么需要在 main.js 中引入对应的组件即可,如下所示。

import { createApp } from 'vue'
import { store, key } from './store';
import router from "./router";
import { ElButtonElSelect } from 'element-plus';
import App from './App.vue';
import './index.css'

const app = createApp(App)
app.component(ElButton.nameElButton);
app.component(ElSelect.nameElSelect);

/* 或者
 * app.use(ElButton)
 * app.use(ElSelect)
 */

app.use(store, key)
app.use(router)
app.mount('#app')

2.6.2 添加配置

引入 Element Plus后,我们可以添加一个全局配置对象。该对象目前支持 size 与 zIndex 字段。size 用于改变组件的默认尺寸,zIndex 设置弹框的初始 z-index。以下是两种不同的引入方式:全局引入:

import { createApp } from 'vue'
import ElementPlus from 'element-plus';
import App from './App.vue';

const app = createApp(App)
app.use(ElementPlus, { size'small'zIndex3000 });

按需引入:

import { createApp } from 'vue'
import { ElButton } from 'element-plus';
import App from './App.vue';

const app = createApp(App)
app.config.globalProperties.$ELEMENT = option
app.use(ElButton);

2.6.3 配置proxy 和 alias

如果要在Vite中使用alias别名配置和proxy代理配置,那么需要在vite.config.ts文件中进行单独的配置。

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    styleImport({
      libs: [
        {
          libraryName'element-plus',
          esModuletrue,
          ensureStyleFiletrue,
          resolveStyle(name) => {
            return `element-plus/lib/theme-chalk/${name}.css`;
          },
          resolveComponent(name) => {
            return `element-plus/lib/${name}`;
          },
        }
      ]
    })
  ],

  /**
   * 在生产中服务时的基本公共路径。
   * @default '/'
   */
  base'./',
  /**
  * 与“根”相关的目录,构建输出将放在其中。如果目录存在,它将在构建之前被删除。
  * @default 'dist'
  */
  // outDir: 'dist',
  server: {
    // hostname: '0.0.0.0',
    host"localhost",
    port3001,
    // // 是否自动在浏览器打开
    // open: true,
    // // 是否开启 https
    // https: false,
    // // 服务端渲染
    // ssr: false,
    proxy: {
      '/api': {
        target'http://localhost:3333/',
        changeOrigintrue,
        wstrue,
        rewrite(pathStr) => pathStr.replace('/api''')
      },
    },
  },
  resolve: {
    // 导入文件夹别名
    alias: {
      '@': path.resolve(__dirname, './src'),
      views: path.resolve(__dirname, './src/views'),
      components: path.resolve(__dirname, './src/components'),
      utils: path.resolve(__dirname, './src/utils'),
      less: path.resolve(__dirname, "./src/less"),
      assets: path.resolve(__dirname, "./src/assets"),
      com: path.resolve(__dirname, "./src/components"),
      store: path.resolve(__dirname, "./src/store"),
      mixins: path.resolve(__dirname, "./src/mixins")
    },
  }
})

其中,vite-plugin-style-import是一个可以按需引入样式的库。

三、数据请求

Vue本身是不支持ajax调用的,如果需要执行网络请求,那么就需要借助一些工具,如superagent和axios。不过,Vue开发使用得比较多的还是axios。

//npm
npm insall axios -save

//yarn 
yarn add axios -save

然后,新建一个request.ts,添加如下的代码。

import axios from 'axios';

let request = axios.create({
    baseURL'http://localhost:3555/api'
})

export default request;

然后,在新建一个index.ts,用来处理具体的网络请求,比如:

import request from "./axios";

export const getUrl = () => {
    return request({
        url"/users/test" // 请求地址
    })
}

export default { getUrl };

最后,在我们的页面代码中调用上面定义的接口即可。

import { getUrl } from "../api/index"

export default {
    setup() {
        const getUrls = async() =>{
            const res = await getUrl()
            console.log(res)
        }
        onMounted(() => { 
            getUrls()
        })
    }
}

(文本完,感谢阅读)