Vite快速构建Vue3项目

1 Vite简介

Vite 是一个由尤雨溪(Vue.js 作者)开发的构建工具,它旨在提供更快的开发体验,尤其适用于现代 JavaScript 框架(如 Vue、React 等)。以下是关
Vite核心特点:
1.快速冷启动
传统构建工具(如 Webpack)在启动开发服务器时,需要对整个项目进行打包编译,这可能会花费较长时间。而 Vite 利用浏览器原生 ES 模块的支持,跳过了打包过程,直接启动开发服务器,实现了秒级的冷启动。
即时热更新(HMR)
2.Vite 提供了高效的热更新机制,当修改代码时,它能够快速更新页面,而不需要重新加载整个页面。这大大提高了开发效率,尤其是在开发大型项目时。
3.按需编译
Vite 只有在浏览器请求模块时才进行编译,避免了不必要的编译工作,减少了开发时的等待时间。
支持多种框架
Vite 不仅支持 Vue,还支持 React、Svelte 等多种前端框架,具有很好的通用性。

2 安装与使用

2.1 使用 npm安装vite

npm install vite -g

2.2 使用vite构建vue3

执行命令

npm create vite

输入项目名字



选择框架-vue



选择js标准-JavaScript
进入项目目录,安装默认依赖及vue-router,axios
cd shop
npm i
npm i vue-router
npm i axios

3 项目初始化

3.1 删除默认生成的代码

11.png

修改App.vue

<template>
  <router-view></router-view>
</template>

修改style.css

html,body,div,span,h1,h2,h3,h4,h5,h6,ul,ol,li,p {
    margin: 0;
    padding: 0;
    font-family: "微软雅黑";
}
html,body,#app {
    /*必须要设置,这样总容器高度才能100%*/
    width: 100%;
    height: 100%;
}
ul,ol {
    list-style: none;
}
a {
    text-decoration: none;
}

3.2 创建路由文件,及修改main.js使用路由

router/index.js

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


const routes = [

]

//创建路由实例
const router = createRouter({
    history: createWebHashHistory(),
    routes
  });
  
export default router;

main.js

import { createApp } from 'vue'
import App from './App.vue'
import './style.css'
import router from './router';

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

3.3 创建 axios 实例并封装,配置拦截器

新建api/index.js

import axios from 'axios';

// 创建 axios 实例
const request = axios.create({
    timeout: 3000 // 请求超时时间
});

// 请求拦截器
request.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        // 处理请求错误
        console.log('请求错误:',error); // 打印错误信息
    }
);

// 响应拦截器
request.interceptors.response.use(
    response => {
        // 获取响应数据
        const res = response.data;
        //直接返回响应数据
        return res;
    },
    error => {
        // 处理响应错误
        console.log('响应错误' + error); // 打印错误信息
    }
);

export default request;

3.4 配置代理服务器,解决Ajax请求跨域访问问题

修改vite.config.js,增加代理服务器配置

server: {
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:7000', //微服务gatewayurl
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容