作者
日期
节日
元公子
2020-10-01(周四)
国庆+中秋
你知道的越少,你不知道的就越少
目标介绍
先集成基本框架:Vue3 + Ant Design + TypeScript + Router + Vuex
然后整个注入全局变量
- app.config.globalProperties
- provide/inject
安装环境
对齐node版本
powershell
PowerShell 7.1.0-preview.7
Copyright (c) Microsoft Corporation.
https://aka.ms/powershell
Type 'help' to get help.
PS D:\develop\CodeProject\jsproject> node -v
v14.12.0
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
yarn全局环境(vue3默认使用yarn)
powershell
PS D:\develop\CodeProject\jsproject> npm install -g yarn
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
vue3全局环境
powershell
PS D:\develop\CodeProject\jsproject> npm install -g @vue/cli
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
查看是否安装成功
powershell
PS D:\develop\CodeProject\jsproject> vue -V
vue: The term 'vue' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
如果出现上面的错误信息,则需要把下面的npm地址信息加入到windows Path环境变量中,然后重启dos窗口或者vscode再次验证。
powershell
PS D:\develop\CodeProject\jsproject> npm config get prefix
D:\develop\nodejs\modules\npm
# 再次验证
PS D:\develop\CodeProject\jsproject> vue -V
@vue/cli 4.5.6
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
初始化项目
通过向导方式构建项目
powershell
PS D:\develop\CodeProject\jsproject> vue create vue3-study
Vue CLI v4.5.6
? Please pick a preset:
vue-framework ([Vue 2] router, vuex, less, babel, eslint, unit-jest)
Default ([Vue 2] babel, eslint)
Default (Vue 3 Preview) ([Vue 3] babel, eslint)
> Manually select features # 选择自定义
# 使用空格键选择下面的选项
? Check the features needed for your project:
>(*) Choose Vue version
(*) Babel
(*) TypeScript
( ) Progressive Web App (PWA) Support
(*) Router
(*) Vuex
(*) CSS Pre-processors
(*) Linter / Formatter
(*) Unit Testing
( ) E2E Testing
# 选择第3版本
? Choose a version of Vue.js that you want to start the project with
2.x
> 3.x (Preview)
# 默认回车(N)不使用class风格的组件语法
? Use class-style component syntax? (y/N)
# 默认回车(Y)使用babel做转义
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? (Y/n)
# 默认回车(Y)使用历史模式(不使用哈希模式)
? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n)
# 选择Sass/SCSS (with dart-sass)
> Sass/SCSS (with dart-sass)
Sass/SCSS (with node-sass)
Less
Stylus
# 选择严格模式
? Pick a linter / formatter config:
ESLint with error prevention only
ESLint + Airbnb config
ESLint + Standard config
> ESLint + Prettier
TSLint (deprecated)
# 默认保存时
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) Lint on save
( ) Lint and fix on commit
# 默认选择 Mocha框架和Chai断言库
? Pick a unit testing solution: (Use arrow keys)
> Mocha + Chai
Jest
# 默认存放到独立的文件
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
> In dedicated config files
In package.json
# 默认回车(N)不设置自定义名字(如果输入y,可设置自定义组合名称,用于下次创建项目,快捷选择自己定义的组合)
? Save this as a preset for future projects? (y/N)
Initializing git repository...
Installing CLI plugins. This might take a while...
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
验证项目是否构建成功
powershell
Successfully created project vue3-study.
Get started with the following commands:
$ cd vue3-study
$ npm run serve
PS D:\develop\CodeProject\jsproject> cd vue3-study
PS D:\develop\CodeProject\jsproject\vue3-study> npm run serve
App running at:
- Local: http://localhost:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
No issues found.
# 也可使用yarn serve
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
集成Ant Design UI
安装库
powershell
PS D:\develop\CodeProject\jsproject\vue3-study> npm install ant-design-vue@next -S
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
开始准备按需引入组件
在src目录下创建plugins子文件夹,并在其下面创建2个ts文件:index.ts,antd.ts
- /src/plugins/index.ts
typescript
import { createApp } from "vue"
/**
* @description 加载所有Plugins
* @param {ReturnType<typeofcreateApp>} app 整个应用的实例
*/
export function loadAllPlugins(app: ReturnType<typeof createApp>) {
const files = require.context('.', true, /\.ts$/)
files.keys().forEach((key) => {
if (key !== './index.ts') files(key).default(app)
})
}
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
- /src/plugins/antd.ts
typescript
import { Button, Card, Row, Col, Tag, Form, Input } from "ant-design-vue"
import { createApp } from "vue"
/**
* @description 手动注册 antd-vue 组件,达到按需加载目的
* @description Automatically register components under Button, such as Button.Group
* @param {ReturnType<typeof createApp>} app 整个应用的实例
* @returns void
*/
export default function loadComponent(app: ReturnType<typeof createApp>) {
app.use(Button)
app.use(Card)
app.use(Row)
app.use(Col)
app.use(Tag)
app.use(Form)
app.use(Input)
}
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
修改入口文件main.ts
typescript
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import { loadAllPlugins } from "@/plugins"
const app: ReturnType<typeof createApp> = createApp(App)
loadAllPlugins(app)
app
.use(store)
.use(router)
.mount("#app")
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
找到HelloWorld.vue,在h1标签下面增加按钮组件测试
vue
<div class="hello">
<h1>{{ msg }}</h1>
<a-button type="primary">
Primary
</a-button>
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
此时按钮已显示,但无样式,下面配置按需引入样式。编辑babel.config.js,plugins属性为增加部分
ps:如果style: "css"改为style: true,需要引入less、less-loader等一系列库,具体按错误提示增加安装
js
module.exports = {
presets: ["@vue/cli-plugin-babel/preset"],
plugins: [
['import', {
libraryName: 'ant-design-vue',
libraryDirectory: 'es',
style: "css"
}]
]
};
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
引入babel-plugin-import库
powershell
PS D:\develop\CodeProject\jsproject\vue3-study> npm install babel-plugin-import -D
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
启动服务,测试显示正常
注入全局变量
在src目录下创建config子文件夹,并在其下面创建1个ts文件:app.ts
- /src/config/app.ts
typescript
/** 跟应用全局相关的静态配置放在这里 */
import { message } from "ant-design-vue"
// 防止弹出大量消息
message.config({
duration: 2,
maxCount: 1
});
const AppConfig = {
$message: message
}
export { AppConfig }
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
修改main.ts
typescript
import { AppConfig } from "@/config/app"
# 测试两种注入方式
app.config.globalProperties = AppConfig
app.provide("AppConfig", AppConfig)
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
修改.eslintrc.js,rules配置项增加不检查any类型
typescript
rules: {
......
'@typescript-eslint/no-explicit-any': 'off',
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
HelloWorld.vue按钮组件增加点击事件
vue
<a-button type="primary" @click="handleMessage">
Primary
</a-button>
......
<script lang="ts">
import { defineComponent, inject, getCurrentInstance } from "vue";
export default defineComponent({
name: "HelloWorld",
props: {
msg: String
},
setup(){
const appConfig: any = inject("AppConfig")
const ctx: any = getCurrentInstance()
function handleMessage() {
// 第一种inject
appConfig.$message.info('This is a normal message')
// 第二种globalProperties
ctx.appContext.config.globalProperties.$message.info('This is a normal message')
}
return{
handleMessage
}
}
});
</script>
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
踩坑记录
选择Less 可能遇到的问题
降低less版本
powershell
PS D:\develop\CodeProject\jsproject\vue3-study> npm uninstall less
PS D:\develop\CodeProject\jsproject\vue3-study> npm uninstall less-loader
PS D:\develop\CodeProject\jsproject\vue3-study> npm install less@2 -D
PS D:\develop\CodeProject\jsproject\vue3-study> npm install less-loader@5 -D
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
按出错提示信息来安装v16库
powershell
PS D:\develop\CodeProject\jsproject\vue3-study> npm install vue-loader-v16 -D
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
core-js库缺少文件时的问题
重装
powershell
PS D:\develop\CodeProject\jsproject\vue3-study> npm install core-js@3 -S
// Js中文网 -前端Vue3源码解析 https://www.javascriptc.com/
作者:元公子
链接:https://juejin.im/post/6878320007072186382
看完两件小事
如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:
- 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
- 关注公众号 「画漫画的程序员」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程