# 编译插件

# 编译插件详解

编译插件类似gulp的plugin或webpck的loader。基于插件能力,用户可以对源码进行代码转义、代码注入等操作。例如将px转化为rpx插件。

# 如何使用插件

// 项目的tms.config.js配置plugins即可
const px2rpx = require('./px2Rpx')
{
  plugins: [{
    glob: '**/*.{wxss,less}' // glob匹配启用插件的文件
    action: px2rpx({screenWidth: 750}) // 插件的实现
  }]
}
1
2
3
4
5
6
7
8

# 如何写编译插件

// px转rpx示例
function px2Rpx({screenWidth}) { // 上文插件传进来参数 screenWidth
  return function ({ vinyl, next, tmsConfig, sourceFile, targetFile, isDev,  }) { // 插件通用参数,详见见下文
    if (vinyl.isBuffer()) { // 根据文件类型,进行操作
      let contents = String(vinyl.contents); // vinyl.content可以拿到当前编译文件的内容
      // 插件处理操作,处理contents即可
      vinyl.contents = Buffer.from(contents); // contents操作完成后,将contents赋值给file.contents
    }
    next(); // 插件执行完毕后,执行回调,执行给其他插件
  };
}
module.exports = px2Rpx;
1
2
3
4
5
6
7
8
9
10
11
12
字段 字段类型 配置说明
vinyl String vinylFile对象 (opens new window)
next Function 插件回调函数,插件执行
tmsConfig String tms.config.js配置的所有配置项
sourceFile String 源码文件所在的目录
targetFile String 编译到哪的文件目录

创建插件时,可直接使用tmskit create <插件名称>初始化编译插件,进项创建

Last Updated: 8/15/2022, 19:19:13