Vite 开发快速入门
SegmentFault
共 18146字,需浏览 37分钟
·
2021-07-28 11:09
作者:xiangzhihong
来源:SegmentFault 思否社区
一、Vite简介
Vite (法语意为 "快速的",发音 /vit/) 是一种面向现代浏览器的一个更轻、更快的前端构建工具,能够显著提升前端的开发体验。除了Vite外,前端著名的构建工具还有Webpack和Gulp。目前,Vite已经发布了Vite2,Vite全新的插件架构、丝滑的开发体验,可以和Vue3的完美结合。
1.1 Vite组成
Vite构建工具由两部分组成:
一个开发服务器,它基于原生 ES 模块提供了丰富的内建功能,如模块热更新(HMR)。
一套构建指令,它使用 Rollup 打包你的代码,并且它是预配置的,可以输出用于生产环境的优化过的静态资源。
1.2 浏览器支持
开发环境中:Vite需要在支持原生 ES 模块动态导入的浏览器中使用。
生产环境中:默认支持的浏览器需要支持 通过脚本标签来引入原生 ES 模块 。可以通过官方插件 @vitejs/plugin-legacy 支持旧浏览器。
二、环境搭建
2.1 创建项目
npm init vite@latest 项目名
yarn create vite 项目名
# 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
2.2 集成Vue-Router
2.2.1 安装配置Vue-Router
//npm
npm install vue-router@next --save
//yarn
yarn add vue-router@next --save
import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/', component: () => import('views/home.vue') }
]
});
export default router
import router from './router';
createApp(App).use(router).mount("#app");
2.2.2 新增路由页面
routes: [
{
path: "/home",
name: "Home",
alias: "/",
component: () => import("../pages/Home.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
//npm
npm install vuex@next --save
//yarn
yarn add vuex@next --save
import { createStore } from "vuex";
const store = createStore({
modules: {
home: {
namespaced: true,
state: {
count: 1
},
mutations: {
add(state){
state.count++;
}
}
}
}
})
export default store;
import { createApp } from 'vue';
import App from './App.vue';
import store from "./store";
const app = createApp(App);
app.use(store);
app.mount('#app');
<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>
2.4 集成Eslint
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 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
{
"root": true,
"env": {
"browser": true,
"node": true,
"es2021": true
},
"extends": [
"plugin:vue/vue3-recommended",
"eslint:recommended",
"@vue/typescript/recommended"
],
"parserOptions": {
"ecmaVersion": 2021
}
}
{
"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
{
"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
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' },
]
}
});
{
"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
npm install element-plus --save
2.6.1 引入element-plus
import { createApp } from 'vue'
import ElementPlus from 'element-plus';
i
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
npm install babel-plugin-component --save
{
"plugins": [
[
"component",
{
"libraryName": "element-plus",
"styleLibraryName": "theme-chalk"
}
]
]
}
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 添加配置
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
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")
},
}
})
三、数据请求
//npm
npm insall axios -save
//yarn
yarn add axios -save
import axios from 'axios';
let request = axios.create({
baseURL: 'http://localhost:3555/api'
})
export default request;
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()
})
}
}
评论