1.进入到文件夹中
2.输入
npm init vite
3.自由选择,然后回车
4.进入到创建好的项目中
输入 npm i
安装依赖
5.修改vite.config.ts
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
//设置全局路径
"@": resolve(__dirname, "./src"),
},
},
base: "./", // 打包路径
server: {
// host: "192.168.10.107", //设置ip,方便调试
host: "0.0.0.0", //设置ip,方便调试
https: false, //是否启动https
port: 8080, // 服务端口号
open: false, //服务启动时候是否自动打开浏览器
cors: true, //是否允许跨域
proxy: {
//设置代理
// 如果是 /apiUrl 打头,则访问地址如下
"/apiUrl": {
target: "http://127.0.0.1:8990/", //代理接口
changeOrigin: true,
rewrite: (path) => path.replace(/^\/apiUrl/, ""),
},
},
},
// 打包配置
build: {
target: "modules",
outDir: "dist", //指定输出路径
assetsDir: "assets", // 指定生成静态资源的存放路径
minify: "terser", // 混淆器,terser构建后文件体积更小
},
});
6.运行
npm run dev
7.打包
npm run build
打包的时候要注意,用了TS的话打包可能会错,是使用TS语法不严谨导致的
解决办法:
打包时关闭TS检测
修改之前
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview"
},
修改之后
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
8.安装less
npm i less-loader less --save-dev
9.配置全局变量,解决页面中变量引入之前都需要单独引入的问题
npm i style-resources-loader
npm i vue-cli-plugin-style-resources-loader
创建 vue.config.js,加入下面配置
const path = require("path");
module.exports = {
transpileDependencies: ["vuetify"],
pluginOptions: {
"style-resources-loader": {
preProcessor: "less",
patterns: [
// 引入公共文件
path.resolve(__dirname, "./src/assets/style/common.less"),
],
},
},
css: {
loaderOptions: {
less: {
lessOptions: {
modifyVars: {
"primary-color": "#ec6800",
},
javascriptEnabled: true,
},
},
},
},
};
10.使用 vue-router
npm i vue-router
创建文件 src/router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
const routes: Array<RouteRecordRaw> = [
{
path: "/Home",
name: "Home",
component: () => import("@/view/home/home.vue"),
// children: [
// {
// path: "/Home/about",
// name: "about",
// component: () => import("@/view/about/about.vue"),
// },
// ],
},
{
path: "/404",
name: "notFound",
component: () => import("@/view/notFound.vue"),
},
{
path: "/about",
name: "about",
component: () => import("@/view/about/about.vue"),
},
{ path: "/", redirect: { name: "Home" } },
{
path: "/:catchAll(.*)", //"/:pathMatch(.*)",
redirect(to) {
if (to.path === "/") {
return "/Home";
} else {
//404
return "/Home";
}
},
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
在main.ts中注册
import router from "./router/index";
const app = createApp(App);
app.use(router);
app.mount("#app");