Skip to content

Issue with binary loaders + workaround #92

@jameschao

Description

@jameschao

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 evanw/esbuild#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,
        };
    },
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions