aelbore / esbuild-jest

A Jest transformer using esbuild
519 stars 51 forks source link

How to set up jest with emotion's css prop support #66

Open kelly-tock opened 2 years ago

kelly-tock commented 2 years ago

https://github.com/evanw/esbuild/issues/832#issuecomment-1021663564

repeated here for consistency:

Thanks @hardfist, for those looking to get emotion working with esbuild, the relevant config is this:

jsxFactory: "jsx",
inject: [path.join(__dirname, "react-shim.js")],

and in react-shim.js

import {jsx} from "@emotion/react";
export {jsx};

And thanks @evanw ! Build time went from 2 minutes to 1.9s 😅

with this setup still getting:

Test suite failed to run

    ReferenceError: jsx is not defined

jest config:

transform: {
    '^.+\\.(js|jsx|ts|tsx)$': [
      'esbuild-jest',
      {
        jsxFactory: 'jsx',
        jsxFragment: 'Fragment',
        inject: [path.join(__dirname, 'react-shim.js')],
      },
    ],
  },

react-shim.js

import { Fragment } from 'react';
import { jsx } from '@emotion/react';

export { jsx, Fragment };

any ideas?

cain-wang commented 2 years ago

One workaround we have is to add a wrapper transformer on top to inject the emotion pragma:

const { createTransformer } = require('esbuild-jest')
const emotionPragma = `const { jsx: emotionJsx } = require('@emotion/core')`

const transformer = createTransformer({
  jsxFactory: 'emotionJsx',
})

module.exports = {
  process(src, filename, jestOptions) {
    const { code, map } = transformer.process(src, filename, jestOptions)

    return {
      code: `${emotionPragma};${code}`,
      map,
    }
  },
}