aelbore / esbuild-jest

A Jest transformer using esbuild
519 stars 51 forks source link

Issue with `binary` loaders + workaround #92

Open jameschao opened 1 year ago

jameschao commented 1 year ago

Hi, I found that esbuild-jest doesn't work with binary loaders, i.e., it results in incorrect data.

It turns out this, it's because rather than using the source code text that jest provides (which seems to have certain encoding), esbuild-jest should pass the actual file contents to esbuild.transformSync().

esbuild v0.14.52 added a fix for handling binary contents properly in transform, and this was referenced https://github.com/evanw/esbuild/issues/2424 also.

I have a working solution, and tried to contribute back, but there were other package version changes, so I was afraid of breaking other things unintentionally. So, decided to raise an issue here instead.

Here's my workaround by adding a custom jest transformer:

const { transformSync } = require('esbuild');
const { readFileSync } = require('fs');

/**
 * This transformer is used to transform binary files using esbuild.
 *
 * This is needed because esbuild-jest currently does not handle binary files transformation properly.
 */
module.exports = {
    process(sourceText, sourcePath) {
        // read the file contents directly rather than using sourceText,
        // which is a string rather than the actual data
        const fileData = readFileSync(sourcePath);
        const { code } = transformSync(fileData, { loader: 'binary' });

        return {
            code,
        };
    },
};