Module not found error when using Puppeteer 21.3.8 in React app

I’m having trouble with Puppeteer 21.3.8 in my React project. I’m using it to make PDFs from HTML and CSS. The problem is that when I try to run tests, I get this error:

Cannot find module 'puppeteer-core/internal/puppeteer-core.js' from 'puppeteer.js'

This happens with Jest 24.9.0 and React-testing-library. The weird thing is, older versions of Puppeteer (before 19.4.0) work fine with the tests, but they mess up my PDF generation.

I’ve tried:

  1. Going back to Puppeteer 18.1.0 (tests work, but PDF doesn’t)
  2. Using versions between 18.1.0 and 21.3.8 (either tests or PDF work, not both)
  3. Using puppeteer-extra and messing with executablePath() (no luck)

Any ideas on how to fix this without going back to an old version? The PDFs are important for my project. Thanks for any help!

Have you considered using a custom Jest transformer for Puppeteer? This approach can sometimes resolve module resolution issues without compromising functionality.

Create a file named ‘jest-puppeteer-transformer.js’ in your project root:

module.exports = {
  process() {
    return { code: 'module.exports = {}' };
  },
};

Then update your Jest config to use this transformer for Puppeteer:

transform: {
  '^.+\.js$': 'babel-jest',
  'node_modules/puppeteer/.+\.js$': '<rootDir>/jest-puppeteer-transformer.js',
}

This method effectively mocks Puppeteer during tests while allowing it to function normally in your main code. It’s worked well for me in similar situations, maintaining both test integrity and PDF generation capabilities.

I’ve dealt with similar Puppeteer issues in React projects. One thing that worked for me was updating Jest to version 29+. It handles the newer Puppeteer structure better.

Also, double-check your Node version. Puppeteer needs at least Node 14. If you’re below that, upgrading could solve the problem.

If those don’t work, try setting Puppeteer as an external dependency in your Webpack config. It prevents Webpack from trying to bundle Puppeteer, which can cause issues.

Lastly, if you’re okay with a slight compromise, you could use puppeteer-core instead of the full Puppeteer. It’s lighter and sometimes avoids these conflicts, but you’ll need to provide your own Chrome binary.

Hope one of these solutions helps you out. Puppeteer can be tricky, but it’s worth the effort for its PDF capabilities.

hey there! i had similar issues. have u tried updating jest to v29+? that fixed it for me. also, check ur node version - puppeteer needs 14 or higher. if ur using webpack, try setting puppeteer as an external dependency. hope this helps!