须知
本文是在 webpack 基础使用 的配置基础上添加 vue3 项目。
安装
需要安装的依赖:
- vue
vue 核心库 - vue-router
vue 路由库 - less
less 预处理器,用来编写样式 - axios
请求库 - mockjs
模拟数据库 - @babel/core
babel 核心库,可以不安装,但如果编译时报错缺少该库,就需要安装 - vue-loader
vue 文件模块加载器 - less-loader
less 文件模块加载器 - css-loader
css 文件模块加载器 - style-loader
安装了 css-loader,就必须安装 style-loader,用途是将样式添加到页面的 head 中
安装运行依赖
1
| npm install vue vue-router less axios mockjs -S
|
安装开发依赖
1
| npm install @babel/core vue-loader less-loader css-loader style-loader -D
|
配置文件修改
webpack.config.js
webpack.config.js 需要修改的地方如下
注意,下列是增加的配置项,不是最终的配置项
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const { VueLoaderPlugin } = require("vue-loader");
module.exports = { module: { rules: [ { test: /\.vue$/i, loader: "vue-loader", }, { test: /\.css$/i, use: ["style-loader", "css-loader"], }, { test: /\.less$/i, use: ["style-loader", "css-loader", "less-loader"], }, ], }, plugins: [new VueLoaderPlugin()], };
|
源码文件
/public/index.html
1 2 3 4 5 6 7 8 9 10 11
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div id="app"></div> </body> </html>
|
/src/main.js
入口文件
1 2 3 4 5 6 7
| import { createApp } from "vue"; import router from "@/router"; import App from "@/App.vue";
const app = createApp(App); app.use(router); app.mount("#app");
|
/src/App.vue
根组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <RouterView /> </template>
<script setup> import { ref } from "vue";
const name = ref("根组件"); </script>
<style lang="less"> // 这里不使用“scoped”,引入全局自定义样式文件 @import url("@/assets/css/less/customGlobal.less"); </style>
|
/src/router/index.js
路由配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import { createRouter, createWebHashHistory } from "vue-router";
const Home = () => import("@/views/Home.vue"); const User = () => import("@/views/User.vue");
const router = createRouter({ history: createWebHashHistory(), routes: [ { path: "/home", name: "home", component: Home }, { path: "/", redirect: "/home" }, { path: "/user", name: "user", component: User }, ], }); export default router;
|
/src/views/Home.vue
主页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <div id="home">{{ name }}</div> </template>
<script setup> import { ref } from "vue";
const name = ref("Home"); </script>
<style lang="less" scoped> #home { background-color: gray; } </style>
|
/src/views/User.vue
用户页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <div id="user">{{ name }}</div> </template>
<script setup> import { ref } from "vue";
const name = ref("User"); </script>
<style lang="less" scoped> #user { background-color: green; } </style>
|
/src/assets/css/less/customGlobal.less
自定义全局 less 样式文件
1 2 3 4 5 6 7 8 9 10 11
|
* { box-sizing: border-box; }
body { margin: 0; }
|