VueCLI项目工程化详解
2022年6月4日大约 3 分钟约 766 字
通常来说前端项目功能较为复杂时,这个时候要对前端项目进行工程化,可以极大地提高开发效率。
下面介绍如何进行工程化:
安装node.js环境
下载安装node.js LTS长期支持版:node.js官网下载
选装nrm
nrm可以非常方便的切换npm安装源,可以很容易切换到国内源
npm install nrm -g
nrm ls # 查看可用的进行源
nrm use taobao # 使用淘宝npm镜像源
安装VueCLI脚手架工具
npm install @vue/cli -g
npm update @vue/cli -g # 已经安装过的可以进行升级
vue -V # 查看版本
创建一个项目
vue craete demo
- Manually select features (人工选择)
- 选择
Babel
Router
Vuex
CSS Pre...
Linter...
- 不使用历史模式路由
- 使用Scss
- ESLint 仅包含错误的ESLint
- Lint on save (每次保存用Lint检查)
- In dedicated config files (Lint配置保存到单独文件)
更新项目内的包(可选)
npm install npm-check-updates -g # 全局安装 包更新器
cd demo
ncu # 查看可更新的包
ncu -u # 更新package.json内容
rm node_modules # 删除包文件,准备重新下载
npm install # 下载包
启动项目
npm run serve
安装Prettier格式化工具
在插件市场可以直接安装Prettier即可。
Prettier网站:中文官网
Prettier配置文件:
.prettierrc
{
"semi": false, // 不尾随分号
"singleQuote": true, // 使用单引号
"trailingComma": "none", // 多行逗号中,最后一行不添加逗号
"printWidth": 320, // 超过多少字符自动换行
"wrapAttributes": false // html标签属性不换行
}
最后在IDE中设置为在保存时格式化文件
配置ESLint规则
.eslintrc.js
module.exports = {
rules: {
// ...
'space-before-function-paren': 'off' // 关闭函数名后需空格的规则
}
}
最后在IDE中安装ESLint插件
初始化代码
App.vue
<template>
<router-view />
</template>
<style lang="scss"></style>
router/index.js
import { createRouter, createWebHashHistory } from 'vue-router'
const routes = []
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
删除views文件下所有.vue文件
删除components文件夹下所有.vue文件
导入element-plus
控制台
vue add element-plus
App.vue
<template>
<router-view />
</template>
<script>
export default {
name: 'App'
}
</script>
<style></style>
选项:
- 选择全局导入
- 不生成覆盖变量的scss文件
- 选择简体中文
构建一个登陆页面
views/login/index.vue
<template>
<div class="">登陆页面</div>
</template>
<script setup>
import {} from 'vue'
import { Avatar } from '@element-plus/icons'
</script>
<style lang="scss" scoped></style>
router/index.js
/**
* 公开路由表
*/
const publicRoutes = [
{
path: '/login',
component: () => import('@/views/login/index')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes: publicRoutes
})
styles/index.scss
/* 全局样式 */
html, body {
height: 100%;
margin: 0;
padding: 0;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
Microsoft YaHei, Arial, sans-serif;
}
#app {
height: 100%;
}
*, *:before, *:after {
box-sizing: inherit;
margin: 0;
padding: 0;
}
a:focus, a:active {
outline: none;
}
a, a:focus, a:hover {
cursor: pointer;
color: inherit;
text-decoration: none;
}
div:focus {
outline: none;
}
.clearfix {
&:after {
visibility: hidden;
display: block;
font-size: 0;
content: ' ';
clear: both;
height: 0;
}
}
main.js
// 导入全局样式
import '.styles/index.scss'