prismicio / prismic-react

React components and hooks to fetch and present Prismic content
https://prismic.io/docs/technologies/homepage-reactjs
Apache License 2.0
153 stars 40 forks source link

Incompatible with Jest using ESM (`Jest encountered an unexpected token`) #160

Closed FrozenKiwi closed 1 year ago

FrozenKiwi commented 1 year ago

Versions

Reproduction

When imported into Jest with Native Modules, it fails to compile because the package exports points to an ESM file, but there is no matching type: "modules" in package.json

https://github.com/prismicio/prismic-react/blob/master/package.json

I think webpack might figure this one out automatically, but jest is bit of a stickler for the rules.

https://github.com/facebook/jest/issues/11809#issuecomment-1048704932

Steps to reproduce

Too many to list. Getting jest going with ESM is a PITA

What is expected?

import succeeds

What is actually happening?

Jest encountered an unexpected token

WORKAROUND:

I'm using a custom resolver with a packageFilter similar to https://github.com/facebook/jest/issues/2702#issuecomment-338071583 that monkey-patches the package on-the-fly.

function mapModuleFieldToExports (pkg, pkgDir) {
  // manually force prismic/react to be a module
  if (pkgDir.includes(`@prismicio${path.sep}react`))
    pkg.type = "module";
angeloashmore commented 1 year ago

Hi @FrozenKiwi, thanks for the report, and sorry for the delay in response.

When we don't get a reproduction project or steps to reproduce the issue, it takes longer for us to diagnose the issue since we need to first recreate the issue. A repro would be greatly appreciated next time. 🙂

Here's a minimal reproduction for this issue: https://github.com/angeloashmore/prismic-react-issue-160-repro


We initially had "type": "module" in this package, along with other Prismic packages, but had to roll back native ESM support due to the ecosystem not being ready. Jest was notably one of the tools that was not ESM-ready at the time we rolled back support.

You can find more details about removing "type": "module" and .mjs in this PR: https://github.com/prismicio/prismic-react/pull/122

Due to Create React App 4's large user-base and ESM still being experimental in many tools (including Jest), I don't think we are ready to commit to full native ESM support.

Until the ecosystem catches up, I think your workaround is the best solution.

I'm going to rename the title of this issue so it is easier to find and we can reference it in the future. I am going to close the issue, however, as it is not something we will be changing soon.

We can definitely continue the conversation here as things change or if you have any suggestions on how we could support it. Thank you! 🙂