Vue3 + Vite项目工程化搭建

Vue3 + Vite项目工程化搭建

安装 Vite

1
npm install -g create-vite

创建项目

1
npm create vite

进入项目目录

1
2
# 进入项目目录
cd my-vite-app

安装依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 安装依赖
npm install
#安装 Element Plus
npm install element-plus
#安装 Vue Router
npm install vue-router
#安装 Pinia
npm install pinia
#安装 Sass,安装时需要添加 -D 参数,表示将 Sass 添加到开发依赖中,在打包过程中,Sass 会自动编译为 CSS
npm install sass -D
#安装 VueUse
npm i @vueuse/core
#安装 Axios
npm install axios
#安装 Echarts
npm install echarts
#安装 Prettier 及相关插件
npm install -D prettier
npm install -D eslint-plugin-prettier
#安装插件
npm install -D unplugin-vue-components unplugin-auto-import

创建目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
cd src
rm -rf components/* modules
mkdir views router store api styles utils layouts
cd views
mkdir dashboard login
touch dashboard/index.vue login/index.vue
mkdir hall
touch hall/index.vue
cd ../router
touch index.js
cd ../store
touch index.js
mkdir modules
touch modules/user.js
cd ../layouts
touch HomeLayout.vue NotFoundLayout.vue
cd ../api
touch user.js
cd ../styles
touch variables.scss
cd ../utils
touch request.js echarts.js
cd ../..

配置 Vite

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
cat << EOF > vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import {ElementPlusResolver} from "unplugin-vue-components/resolvers";
import { resolve } from "path";

// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
// 自动导入
AutoImport({
// 自动导入 Vue 相关函数,如:ref, reactive, toRef 等
imports: ["vue", "vue-router", "@vueuse/core"],
resolvers: [
// 自动导入 Element Plus 相关函数
ElementPlusResolver(),
],
// 配置文件位置 (false:关闭自动生成)
dts: resolve(__dirname, "src/types/auto-imports.d.ts"),
}),
Components({
resolvers: [
// 自动导入 Element Plus 组件
ElementPlusResolver(),
],
// 指定自定义组件位置(默认:src/components)
dirs: ["src/**/components"],
// 配置文件位置 (false:关闭自动生成)
dts: resolve(__dirname, "src/types/components.d.ts"),
}),
],
resolve: {
// 导入文件时省略文件扩展名
extensions: [".js", ".ts", ".vue", ".json", "es"],
// 配置路径别名
alias: { "@": resolve(__dirname, "src") },
},
css: {
// CSS 预处理器
preprocessorOptions: {
// 定义全局 SCSS 变量
scss: {
javascriptEnabled: true,
additionalData: "@use '/src/styles/variables.scss' as *;",
},
},
},
})
EOF

cd src
cat << EOF > views/dashboard/index.vue
<script setup>
import echarts from "@/utils/echarts";
import { onMounted, ref } from "vue";

const chartRef = ref(null);
let echartClient = null;
onMounted(() => {
initChart();
});
function initChart() {
echartClient = echarts.init(chartRef.value);
echartClient.setOption({
tooltip: {},
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
},
yAxis: {},
series: [
{
name: "销量",
type: "bar",
data: [5, 20, 36, 10, 10, 20],
},
],
});
}
</script>
<template>
<div class="chart-box" ref="chartRef"></div>
</template>

<style scoped lang="scss">
.chart-box {
width: 600px;
height: 400px;
}
</style>
EOF

cat << EOF > views/login/index.vue
<!--src/views/login/index.vue-->
<script setup>
import useUserStore from "../../store/modules/user";
import { getCodeInfo } from "../../api/user";
import { onMounted, ref } from "vue";

const userStore = useUserStore();
const captchaInfo = ref("");

/**
* 登录
*/
function login() {
userStore
.handleLogin()
.then((res) => {
ElMessage.success(res);
})
.catch((err) => {
ElMessage.error(err);
});
}

/**
* 退出登录
*/
function loginOut() {
userStore
.handleLogout()
.then(() => {
ElMessage.success("退出登录成功");
})
.catch((err) => {
ElMessage.error(err);
});
}

onMounted(() => {
getCodeInfo(new Date().getTime()).then(({ data }) => {
captchaInfo.value = data.result;
});
});
</script>

<template>
<div class="login-container">
<el-button type="primary" @click="login">登 录</el-button>
<el-button type="primary" @click="loginOut">退出登录</el-button>

<hr />
<h1>当前登录状态:{{ userStore.loginStatus ? "已登录" : "未登录" }}</h1>
<ul>
<li>用户名:{{ userStore.userInfo.name }}</li>
<li>头 像:<img :src="userStore.userInfo.avatar" alt="" /></li>
<li>验证码:<img :src="captchaInfo" alt="" /></li>
</ul>
</div>
</template>
EOF

cat << EOF > App.vue
<template>
<component :is="currentLayout">
<router-view></router-view>
</component>
</template>

<script>
import HomeLayout from './layouts/HomeLayout.vue';
import NotFoundLayout from './layouts/NotFoundLayout.vue';

export default {
data() {
return {
currentLayout: this.getLayout(), // 获取当前布局
};
},
methods: {
getLayout() {
if (this.$route.path === '/404') {
return NotFoundLayout;
}
return HomeLayout;
}
},
watch: {
$route() {
this.currentLayout = this.getLayout(); // 路由变化时切换布局
}
}
};
</script>
EOF

cat << EOF > main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import pinia from "./store";

const app = createApp(App);
app.use(router);
app.use(pinia);
app.mount("#app");
EOF

cat << EOF > utils/request.js
// src/utils/request.js
import axios from "axios";

const request = axios.create({
baseURL: "http://xxx.xxx.xxx.xxx // 请求的后端接口地址",
});
/**
* 请求拦截器
*/
request.interceptors.request.use((config) => {
console.log("请求参数:", config);
});
/**
* 响应拦截器
*/
request.interceptors.response.use((response) => {
console.log("响应参数:", response);
});

export default request;
EOF

cat << EOF > utils/echarts.js
// src/utils/echarts.js

// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from "echarts/core";
// 引入柱状图图表,图表后缀都为 Chart
import { BarChart } from "echarts/charts";
// 引入提示框,标题,直角坐标系,数据集,内置数据转换器组件,组件后缀都为 Component
import {
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
} from "echarts/components";
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from "echarts/features";
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from "echarts/renderers";

// 注册必须的组件
echarts.use([
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
BarChart,
LabelLayout,
UniversalTransition,
CanvasRenderer,
]);

export default echarts;
EOF

cat << EOF > styles/variables.scss
//src/styles/variables.scss
\$success: #48c78e;
\$danger: #f28482;
EOF

cat << EOF > api/user.js
import request from "../utils/request";

/**
* 获取验证码
* @param checkKey
*/
export function getCodeInfo(checkKey) {
return request({
method: "get",
url: '',
});
}
EOF

cat << EOF > store/modules/user.js
// src/store/modules/user.js
import { defineStore } from "pinia";
import { ref } from "vue";

const useUserStore = defineStore("user", () => {
const userInfo = ref({});
const loginStatus = ref(false);
const token = ref("");
/**
* 登录
*/
function handleLogin() {
return new Promise((resolve, reject) => {
if (Math.random() > 0.8) {
loginStatus.value = true;
token.value = String(new Date().getTime());
userInfo.value = {
name: "admin",
avatar: "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80",
};
resolve("登录成功");
} else {
reject("登录失败");
}
});
}

/**
* 退出登录
*/
function handleLogout() {
return new Promise((resolve) => {
loginStatus.value = false;
token.value = "";
userInfo.value = {};
resolve();
});
}

return {
userInfo,
loginStatus,
token,
handleLogin,
handleLogout,
};
});

export default useUserStore;
EOF

cat << EOF > store/index.js
// src/store/index.js
import { createPinia } from "pinia";

const pinia = createPinia();
export default pinia;
EOF

cat << EOF > router/index.js
// src/router/index.js
import {createRouter, createWebHistory} from "vue-router";

const router = new createRouter({
history: createWebHistory(),
routes: [
{
path: "/",
component: () => import("../views/hall/index.vue"),
children: [
{
path: "hall",
component: () => import("../views/hall/index.vue")
}
]
},
{
path: "/login",
name: "Login",
component: () => import("../views/login/index.vue"),
},
{
path: "/dashboard",
name: "Dashboard",
component: () => import("../views/dashboard/index.vue"),
},
],
});
export default router;
EOF

cat << EOF > layouts/HomeLayout.vue
<template>
<header class="header">
<div class="logo">XXX</div>
<div class="search-bar">
<input type="text" placeholder="提问" />
<button>搜索</button>
</div>
<div class="user-actions">
<span>消息</span>
<span>私信</span>
<span>创作中心</span>
<span>草稿箱</span>
<img src="https://img.icons8.com/ios/452/user" alt="用户头像" />
</div>
</header>
<el-main class="main-content">
<router-view></router-view>
</el-main>
</template>

<script>
export default {
name: "HeaderLayout",
data() {
return {
activeMenu: this.getActiveMenu(),
};
},
methods: {
goHome() {
this.$router.push("/home");
},
getActiveMenu() {
const path = this.$route.path;
return "hall";
},
},
watch: {
$route() {
this.activeMenu = this.getActiveMenu();
},
},
};
</script>

<style scoped>
/* Header Styles */
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 30px;
background-color: #ffffff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border-bottom: 1px solid #f0f0f0;
font-family: Arial, sans-serif;
}

.logo {
font-size: 28px;
font-weight: bold;
color: #333;
}

.search-bar {
display: flex;
align-items: center;
position: relative;
}

.search-bar input {
padding: 8px 15px;
border: 1px solid #ccc;
border-radius: 25px;
width: 250px;
font-size: 14px;
outline: none;
transition: border-color 0.3s;
}

.search-bar input:focus {
border-color: #007aff;
}

.search-bar button {
padding: 8px 15px;
background-color: #007aff;
color: white;
border: none;
cursor: pointer;
border-radius: 25px;
position: absolute;
right: -10px;
transition: background-color 0.3s;
}

.search-bar button:hover {
background-color: #0056b3;
}

.user-actions {
display: flex;
align-items: center;
font-size: 14px;
}

.user-actions span {
margin-right: 15px;
cursor: pointer;
transition: color 0.3s;
}

.user-actions span:hover {
color: #007aff;
}

.user-actions img {
width: 36px;
height: 36px;
border-radius: 50%;
border: 2px solid #007aff;
cursor: pointer;
}

/* Main Content Styles */
.main-content {
padding: 20px;
background-color: #f9f9f9;
}
</style>
EOF

cat << EOF > layouts/NotFoundLayout.vue
<script setup>

</script>

<template>
<div>
<h1>404 Not Found</h1>
</div>
</template>

<style scoped>

</style>
EOF

进入package.json文件,修改scripts字段

1
2
3
4
5
6
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"prettier": "prettier --write src/**/*.{vue,js,jsx,ts,tsx,json,css,scss,md}"
},

运行

1
npm run dev

参考