aelbore / esbuild-jest

A Jest transformer using esbuild
516 stars 50 forks source link

Repo Maintenance #69

Open vertic4l opened 2 years ago

vertic4l commented 2 years ago

esbuild + jest is an important improvement, but this repo doesn't seem to be maintained further.

Am i correct ? How can we go on and make life easier for all ?

jzinn commented 1 year ago

For those having problems with esbuild-jest due to lack of maintenance, or due to its dependencies on babel packages, it's easy enough to implement a simple custom transformer.

Besides esbuild-jest, there are other transformer projects such as es-jest, jest-esbuild, esjest-transform, and the babel-based transformer that ships with Jest that you can reference when writing your own.

The official documentation on Code Transformation is also useful.

An example transformer is below.

jest.config.js

Add a transform section to your jest config file that points to wherever you put the transformer file.

The options are passed directly to esbuild and override any default options that would otherwise be passed to esbuild.

module.exports = {
  coverageProvider: "v8",
  transform: {
    "\\.js$": [
      "<rootDir>/path/to/TransformerEsbuild.js",
      {
        loader: "jsx",
        target: "node16",
      },
    ],
  }
};

TransformerEsbuild.js

Put this transformer file wherever you want in your project's directory structure. Update the transform section of your jest config file to point to where you put it.

This transformer does not specify a getCacheKey function, so esbuild transforms every file on every test run. For a small number of files, this version is just as fast as a (not shown) version that does specify a getCacheKey function.

const { transformSync } = require("esbuild");

const defaultOptions = {
  format: "cjs",
  sourcemap: "both",
  target: `node${process.versions.node}`,
};

module.exports = {
  createTransformer(userOptions) {
    return {
      canInstrument: true,
      process(sourceText, sourcePath) {
        const options = {
          ...defaultOptions,
          ...userOptions,
          sourcefile: sourcePath,
        };
        const { code, map } = transformSync(sourceText, options);
        return { code, map };
      },
    };
  },
};
lucasrmendonca commented 3 weeks ago

Check out esbuild-jest2