解决小程序beforeCompile失效问题, 实现antv f2的jsx文件监听修改与自动编译功能

345 阅读1分钟

背景

由于业务需求, 要在微信小程序开发数据可视化, 发现Antv F2版本升级了, 4.0以后的版本使用jsx语法编写图表. 但是微信小程序原生不支持jsx语法, 根据官方教程, 需要使用babel将jsx编译成为js.

问题

根据Antv官方文档的介绍, 需要将运行命令放在package.jsonbeforeCompile中,就能实现自动编译jsx文件. 但是实测没有效果, 只能手动执行.

image.png

我提交了一个ISSUE也没有得到解决方案.

image.png

解决

一键编译所有jsx文件

# !/bin/bash
for file in $(find . -name "*.jsx"); do
    output_file="${file%.*}.js"
    npx babel $file --out-file $output_file
done

文件放在项目根目录下, 文件名为compile.sh , 执行方法 sh compile.sh

遍历所有文件夹, 将jsx文件编译成同名js文件, 放在同级目录中

但是缺点是每次修改jsx文件都需要手动执行

监听jsx文件变化, 自动编译

# !/bin/bash
while true; do
    fswatch -r packageA/pages/daping/chart/ | while read file
    do
        if [[ $file == *.jsx ]]; then
            output_file="${file%.*}.js"
            npx babel $file --out-file $output_file
        fi
    done
done

需要先安装fswatch brew install fswatch, 文件放在项目根目录下, 文件名为compile.sh , 执行方法 sh compile.sh

fswatch监听指定路径下的文件更新, 自动编译. 由于会对fswatch全部文件监听, 最好指定路径减少性能开销.

使用node.js实现

const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');

// 监听文件夹的路径
const jsxDir = './packageA/pages/daping/chart';
  
function compileFile(filePath) {
    const jsPath = path.join(path.dirname(filePath), path.parse(filePath).name + '.js');
    spawn('npx', ['babel', filePath, '--out-file', jsPath]);
}

console.log(`Listening for changes in ${jsxDir}...`);
fs.watch(jsxDir, { recursive: true }, (eventType, fileName) => {
    const filePath = path.join(jsxDir, fileName);

    if (eventType === 'change' && path.extname(filePath) === '.jsx') {
        console.log(`Detected change in ${filePath}`);
        compileFile(filePath);

    }
});

最后想起来项目的其他小伙伴有在使用Windows电脑的, 使用node实现就可以全平台兼容了

可以放在package.json的scripts中, 执行npm run compileJsx即可

"scripts": {
    ...
    "compileJsx": "node compileJsx.js"
},