基于 Vue 的最佳实践

本项目是基于 Web 开发最佳实践 的扩展

解决 globalThis 的问题

参考 : 解决浏览器端 globalThis is not defined 报错
解决方案
<head> 中加入

1
2
3
<script>
this.globalThis || (this.globalThis = this);
</script>

在低版本手机上出现白屏的问题

在低版本手机上访问页面需要对代码打包进行 es2015 转义

1
2
3
4
5
// ...
build: {
target: "es2015";
}
// ...

组件的自动加载

自动加载的弱项
如果组件使用自动加载也可以, 但是需要自动引入 app.use(Comp) 这种方式, 并在配置文件中加入 components
全部加载的弱项
全部加载会在打包的时候 minify 会解析所有的 css 样式, 导致时间过长 (10min+)

所以组件使用 unplugin-vue-components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Components from "unplugin-vue-components/vite";
import { AntDesignVueResolver, ElementPlusResolver, VantResolver } from "unplugin-vue-components/resolvers";
export default defineConfig(({ mode }) => {
return {
// ...
plugins: [
// ...
Components({
resolvers: [AntDesignVueResolver(), ElementPlusResolver(), VantResolver()],
dts: true,
include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
}),
// ...
],
// ...
};
});

移除 console 日志

打包启用 terser, 配置 tersor 的选项

1
2
3
4
5
6
7
8
9
10
11
12
13
export default defineConfig(({ mode }) => {
return {
build: {
// ...
minify: "terser",
terserOptions: {
compress: {
drop_console: true,
},
},
},
};
});

为开发环境提供 https 证书

在开发的时候有时候需要 https 证书(例如浏览器通知需要在 https 证书下才可以打开)
插件 : vite-plugin-mkcert
安装插件

1
yarn add vite-plugin-mkcert -D

配置证书

1
2
3
4
5
6
7
8
9
10
import {defineConfig} from'vite'
import mkcert from'vite-plugin-mkcert'

// https://vitejs.dev/config/
export default defineConfig({
server: {
https: true
},
plugins: [mkcert()]
})

Component name “XXX“ should always be multi-word

找到根目录下的 .eslintrc.js, 加入如下行, 对于文件名不是多文件名称的可以关闭提示

1
2
3
4
5
6
7
8
9
 module.exports = {
...
rules: {
...
+ 'vue/multi-word-component-names': 'off',
...
}
...
};

vue router 新窗口打开页面

1
2
const { href } = router.resolve({ name: 'pc.chat' });
window.open(href, "_blank");

参考


语雀镜像 : 基于 Vue 的最佳实践 ,点此 提问

作者

Duoli

发布于

2022-04-20

更新于

2022-11-05

许可协议

评论