关于前端:Vite开发快速入门

一、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({
  history: createWebHashHistory(),
  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: {
      namespaced: true,
      state: {
        count: 1
      },
      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 { ElButton, ElSelect } from 'element-plus';
import App from './App.vue';
import './index.css'

const app = createApp(App)
app.component(ElButton.name, ElButton);
app.component(ElSelect.name, ElSelect);

/* 或者
 * 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', zIndex: 3000 });

按需引入:

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',
          esModule: true,
          ensureStyleFile: true,
          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",
    port: 3001,
    // // 是否主动在浏览器关上
    // open: true,
    // // 是否开启 https
    // https: false,
    // // 服务端渲染
    // ssr: false,
    proxy: {
      '/api': {
        target: 'http://localhost:3333/',
        changeOrigin: true,
        ws: true,
        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()
        })
    }
}

下一篇:Webpack我的项目如何转Vite

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理