taro-ui-vue3 icon indicating copy to clipboard operation
taro-ui-vue3 copied to clipboard

关于按需引用组件的说明

Open b2nil opened this issue 4 years ago • 3 comments

如需按需引用组件,请从 taro-ui-vue3/lib 目录中引用。 样式按需引用,仍需从 taro-ui-vue3/dist/style 目录中引用。

方式一

import { AtButton } from 'taro-ui-vue3/lib'
import "taro-ui-vue3/dist/style/components/button.scss"

方式二

  • 在 webpack 配置中,将 taro-ui-vue3 的 alias 指向 taro-ui-vue3/lib
// config/index.js
alias: {
  'taro-ui-vue3$': 'taro-ui-vue3/lib'
}
  • 然后从 taro-ui-vue3 中引用组件
 import { AtButton } from 'taro-ui-vue3'
 import "taro-ui-vue3/dist/style/components/button.scss"

b2nil avatar Dec 04 '20 15:12 b2nil

相关 issues:#57、#64

b2nil avatar Dec 04 '20 15:12 b2nil

一些编译后的本地代码大小数据比较:

  • taro-ui-vue3-demo 为例(引用了 taro-ui-vue3 的全部组件)

    编译命令 taro-ui-vue3/lib 引用组件 taro-ui-vue3 (index.esm.js) 引用组件
    dev:weapp 3386 KB 3167 KB
    build:weapp 1363 KB 1348 KB
  • 以一个只有两个页面、分别引用了AtAccordionAtButtonAtFlexAtFlexItemAtAvatar 的 Demo 小程序为例

    编译命令 taro-ui-vue3/lib 引用组件 taro-ui-vue3 (index.esm.js) 引用组件
    dev:weapp 837 KB 1204 KB
    build:weapp 248 KB 404 KB

备注

  • 以上数据来源于微信开发工具 详情 -> 基本信息 -> 本地代码
  • build 配置使用 Taro 默认编译配置

b2nil avatar Dec 05 '20 03:12 b2nil

另外,关于 Webpack 4 Tree Shaking, 根据 webpack 官网说明 以及 这篇博文 的解释,webpack 配置需要做到以下几点:

  • 使用 ES2015 module 语法 (如:importexport)
  • 确保编译器不会将 ES2015 module 语法转译为 CommonJS 模块(例如 Babel preset @babel/preset-env 的默认行为)
  • 在项目的 package.json 文件中添加 sideEffects 属性
  • 必须在 production 模式下
  • 必须将 optimizationusedExports 选项设置为 true
  • 必须使用支持 dead code 移除的压缩插件,如 terser
// 支持 tree shaking 的基本 wepack 配置
const config = {
  mode: 'production',
  optimization: {
    usedExports: true,
    minimizer: [ // 或者使用 minimize: true, 采用默认的 terser 插件配置
       (compliler) => new TerserPlugin({...}).apply(compiler)
    ] 
  }
}

通过以上配置,在 Taro 中无法对 taro-ui-vue3/dist/index.esm.js 实现 tree shake 功能。

b2nil avatar Dec 05 '20 04:12 b2nil