Advertisement

Taro 引入 npm @vant/weapp

阅读量:

安装依赖

复制代码
    # 通过 npm 安装
    npm i @vant/weapp --save
    
    # 通过 yarn 安装
    yarn add @vant/weapp

配置忽略 vant 的样式尺寸转换

如果直接使用 vant 组件,会发现样式偏小的情况,这是因为 Taro 默认将 vant 的样式尺寸从 px 转换为了 rpx,可以通过配置 selectorblacklist 来禁止转换。

复制代码
    // config/index.js
    const config = {
      // ...
      mini: {
    postcss: {
      pxtransform: {
        enable: true,
        config: {
          selectorBlackList: [/van-/]
        }
      }
    }
      },
    }

映射目录

@vant/weapp目录:@vant/weapp/dist
代码目录:src/vant
打包目录:dist/vant

复制代码
    // config/index.js
    const config = {
      // ...
      alias: {
    "/vant": "src/vant",
      },
      copy: {
    patterns: [
      // 供usingComponents编译使用
      { from: "node_modules/@vant/weapp/dist/", to: "src/vant/" },
      // 通用wxs
      { from: "node_modules/@vant/weapp/dist/wxs/", to: "dist/vant/wxs/" },
      // 通用样式
      { from: "node_modules/@vant/weapp/dist/common/style/", to: "dist/vant/common/style/" },
      { from: "node_modules/@vant/weapp/dist/common/index.wxss", to: "dist/vant/common/index.wxss" },
    ],
    options: {}
      },
    }

开始调试

打开开发者工具可以看到目录下通用导入
引入组件

复制代码
    // src/pages/index/index.config.js
    export default {
      navigationBarTitleText: '首页',
      usingComponents: {
    // /vant在config/index.js alias配置
    'van-button': '/vant/button/index'
      }
    }

依赖导入
可以看到usingComponents导入了js,json,wxml,wxss等基本组件文件,生成了map,以及依赖项的组件,同时抛出了错误异常
/vant/button/目录下没有看到index.wxs文件,说明usingComponents不会导入wxs文件,所以我们重新回到copy配置上

检查src/vant目录下的button及其依赖,补充wxs

复制代码
    // config/index.js
    const config = {
      // ...
      copy: {
    patterns: [
      // 供usingComponents编译使用
      { from: "node_modules/@vant/weapp/dist/", to: "src/vant/" },
      // 通用wxs
      { from: "node_modules/@vant/weapp/dist/wxs/", to: "dist/vant/wxs/" },
      // 通用样式
      { from: "node_modules/@vant/weapp/dist/common/style/", to: "dist/vant/common/style/" },
      { from: "node_modules/@vant/weapp/dist/common/index.wxss", to: "dist/vant/common/index.wxss" },
      // 组件依赖,映射目录要清晰
      { from: "node_modules/@vant/weapp/dist/icon/index.wxs", to: "dist/vant/icon/index.wxs" },
      { from: "node_modules/@vant/weapp/dist/loading/index.wxs", to: "dist/vant/loading/index.wxs" },
      { from: "node_modules/@vant/weapp/dist/button/index.wxs", to: "dist/vant/button/index.wxs" }
    ],
    options: {}
      },
    }

重新运行

完成

整理

  1. 官方文档 使用原生模块 目录处于src目录下
  2. Taro中usingComponents引入带有动态导入且编译压缩
  3. alias配置用于处理usingComponents绝对路径
  4. copy用于复制依赖到src和补充usingComponents缺少引入的依赖

结果来说还是标题党了,只是不需要手动复制vant目录,但需要注意,如果vant的依赖版本目录结构产生了变化,copy的补充配置部分就要再次修改。

全部评论 (0)

还没有任何评论哟~