Charklewis
Charklewis

Reputation: 5631

Uncaught Error: Cannot find module 'react/jsx-runtime'

I am exploring making a component library using React and rollup. I'm finding that the app that is consuming the library is bundling it in the wrong order.

This is causing the below error:

bundle.js:99 Uncaught Error: Cannot find module 'react/jsx-runtime'
    at webpackMissingModule (bundle.js:99)
    at Module.../../../component-library/dist/index.es.js 

In the Webpack CLI I also get similar errors:

ERROR in /.../component-library/dist/index.es.js
Module not found: Error: Can't resolve 'react' in '/.../component-library/dist'
 @ /.../component-library/dist/index.es.js 2:0-33 68:18-26
 @ ./src/App/index.jsx
 @ ./src/index.js

ERROR in /.../component-library/dist/index.es.js
Module not found: Error: Can't resolve 'react/jsx-runtime' in '/.../component-library/dist'
 @ /...component-library/dist/index.es.js 1:0-41 74:22-26
 @ ./src/App/index.jsx
 @ ./src/index.js

I have not published the library anywhere, so just using yarn link for now.

In my component library, my rollup config looks like:

import peerDepsExternal from "rollup-plugin-peer-deps-external"
import babel from "@rollup/plugin-babel"
import commonjs from "@rollup/plugin-commonjs"
import resolve from "@rollup/plugin-node-resolve"
const packageJson = require("./package.json")

const config = [
  {
    input: "./src/index.js",
    output: [
      {
        file: packageJson.main,
        format: "cjs",
        sourcemap: true,
      },
      {
        file: packageJson.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    external: Object.keys(packageJson.peerDependencies || {}),
    plugins: [
      peerDepsExternal(),
      resolve(),
      commonjs(),
      babel({ exclude: "node_modules/**", babelHelpers: "bundled" }),
    ],
  },
]

export default config

My babel config

module.exports = {
  presets: [["@babel/preset-env"], ["@babel/preset-react", { runtime: "automatic" }]],
}

My package.json

{
  "name": "component-library",
  "version": "0.0.0",
  "description": "A component library.",
  "main": "dist/index.js",
  "module": "dist/index.es.js",
  "repository": "https://github.com/.../component-library.git",
  "private": true,
  "scripts": {
    "watch": "rollup -c --watch",
    "build": "rollup -c"
  },
  "devDependencies": {
    "@babel/cli": "^7.12.10",
    "@babel/core": "^7.12.10",
    "@babel/preset-env": "^7.12.11",
    "@babel/preset-react": "^7.12.10",
    "@rollup/plugin-babel": "^5.2.2",
    "@rollup/plugin-commonjs": "^17.0.0",
    "@rollup/plugin-node-resolve": "^11.1.0",
    "@testing-library/jest-dom": "^5.11.9",
    "@testing-library/react": "^11.2.3",
    "@testing-library/react-hooks": "^5.0.3",
    "@testing-library/user-event": "^12.6.2",
    "eslint": "^7.18.0",
    "eslint-plugin-jest": "^24.1.3",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-react": "^7.22.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "eslint-plugin-testing-library": "^3.10.1",
    "jest": "^26.6.3",
    "prettier": "^2.2.1",
    "rollup": "^2.38.0",
    "rollup-plugin-peer-deps-external": "^2.2.4"
  },
  "peerDependencies": {
    "react": "^17.0.0",
    "react-dom": "^17.0.0"
  }
}

I can see the code that is output by rollup looks like it is correct:

import { jsxs } from 'react/jsx-runtime';
import { useState } from 'react';

function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}

function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

//continue...

In the bundle that my app's Webpack outputs, it adds the code for the component right near at the top, before any dependencies such as React or the actual app code.

line 76: //prior bundled code...
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = "./src/index.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "../../../component-library/dist/index.es.js":
/*!*******************************************************************!*\
  !*** /.../component-library/dist/index.es.js ***!
  \*******************************************************************/
/*! exports provided: Example */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Example", function() { return Example; });
!(function webpackMissingModule() { var e = new Error("Cannot find module 'react/jsx-runtime'"); e.code = 'MODULE_NOT_FOUND'; throw e; }());
!(function webpackMissingModule() { var e = new Error("Cannot find module 'react'"); e.code = 'MODULE_NOT_FOUND'; throw e; }());

function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}

function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

//continue...

//react/jsx-runtime is set up on line 118391

No matter where I add the component in the App, the code is bundled in the same place. I also tried to include React in my rollup bundle from the library. However, then my app complains about multiple React versions being loaded.

I am not too sure what to try next. I haven't experienced this with any other libraries I have downloaded via npm and used in my app. So this is making me think there is something wrong with my rollup config or build process.

Upvotes: 63

Views: 200124

Answers (17)

Junior Grão
Junior Grão

Reputation: 1661

I know it can be many things related but in my case, I am using VS code and after merging down main branch into my feature branch so these warnings just came up.

So I fixed that updating the packages using yarn in the VS code terminal:

rm -rf node_modules && yarn

Then into the VS code pressing CTRL + SHIFT + P, just typing/select "TypeScript: Restart TS Server"

For me, sometimes VS Code typescript server doesn't pick up new packages and restarting it usually fixes the issue

Upvotes: 0

anon
anon

Reputation:

This solution resolved my issue. I found it over here

👇️ with NPM

npm install react@latest react-dom@latest

👇️ ONLY If you use TypeScript

npm install --save-dev @types/react@latest @types/react-dom@latest

----------------------------------------------

👇️ with YARN

yarn add react@latest react-dom@latest

👇️ ONLY If you use TypeScript

yarn add @types/react@latest @types/react-dom@latest --dev

Upvotes: 45

YinPeng.Wei
YinPeng.Wei

Reputation: 598

Just copy component's source code into your project is a hack way. if you can't resolve this problem, try this. I can't resolve this error by any way I could find. Beside, update react version is unsafe to a big project, it may course a lot of test and unknown error. :) love and peace.

Upvotes: -1

DINA TAKLIT
DINA TAKLIT

Reputation: 8388

Hello I got the same error when I tried to add the graphql playground using graphiql in my docusaurus documentation

import React from "react";
import { createGraphiQLFetcher } from "@graphiql/toolkit";
import { GraphiQL } from "graphiql";
import "graphiql/graphiql.css";

const fetcher = createGraphiQLFetcher({
  url: "https://my.graphql.api/graphql",
});

export default function GraphqlPlayGround() {
  return <GraphiQL fetcher={fetcher} />;
}

I was running into this issue

Module not found: Error: Can't resolve 'react/jsx-runtime' in '/Users/user/Desktop/Saleor/DocAuth0/node_modules/@graphiql/react/dist'
Did you mean 'jsx-runtime.js'?
BREAKING CHANGE: The request 'react/jsx-runtime' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.

To fix this you need to create a custom loader for you webpack configuration to disable this behaviour

Since webpack 5.0.0-beta.30, you're required to specify extensions when using imports in .mjs files or any .js files with a package.json with "type": "module". You can still disable the behavior with resolve.fullySpecified set to false if you see any related errors in your project.

The steps you need to follow for this process are:

  1. Create plugins folder: Create a plugins folder at your project root.
  2. Create a plugin: Create a plugin (e.g., my-loaders) inside the plugins folder with index.js and package.json files:

As noted in the Docusaurus docs for configureWebpack(), the return object highlighted below gets merged into the final webpack config.

/plugins/my-loaders/index.js

module.exports = function (context, options) {
  return {
    name: 'my-loaders',
    configureWebpack(config, isServer) {
      return {
        module: {
          rules: [
            {
              test: /\.m?js/,
              resolve: {
                fullySpecified: false
              }
            },
          ],
        },
      };
    },
  };
};

/plugins/my-loaders/package.json

{
  "name": "my-loaders",
  "version": "0.0.0",
  "private": true
}

3.Update Docusaurus config: Update your Docusaurus configuration file to use the plugin: /docusaurus.config.js

plugins: [
  // ...
  'my-loaders'
  // ...
]

4.Update project dependency list to use plugin: Specify the plugin as a dependency in the package.json at your project root: /package.json

{
  // ...
  "dependencies": {
    // ...
    "my-loaders": "file:plugins/my-loaders",
    // ...
  },
    // ...
}

5.Install new plugin dependency for project: Execute the following to make use of the new plugin in your project:

npm i

Reference: Please follow up [this documentaion] for more details (https://dwf.dev/blog/2022/11/12/2022/updating-docusaurus-webpack-config)

Upvotes: 5

Super Jade
Super Jade

Reputation: 6345

Cannot find module 'react/jsx-runtime'


Solution

  1. Update your version of react and / or react-dom

    npm install react@latest react-dom@latest

  2. If using TypeScript, update the types files

    npm install @types/react@latest @types/react-dom@latest

Upvotes: 1

Guram Khasia
Guram Khasia

Reputation: 206

In my case, this error was fixed by updating babel.config.json. In presets array I changed runtime to classic instead of automatic

  "presets": [
    "@babel/preset-env",
    [
      "@babel/preset-react",
      {
        "runtime": "classic" // changed automatic to classic
      }
    ],
    "@babel/preset-typescript"
  ],

Upvotes: 3

Bryan
Bryan

Reputation: 1

Incase you encounter this issue while developing on vscode using Linux subsystem for windows and pnpm. Ensure you download the following extension https://code.visualstudio.com/blogs/2019/05/02/remote-development then open the folder again on WSL.

Upvotes: 0

Freedisch
Freedisch

Reputation: 221

I got the same error after setting up the project with vite on my subsystem for Linux, and none of the solutions up there worked for me. But after shifting on windows, the error disappeared. I still wonder why? Anyways, If you have the same issue and are on WSL, consider setting the project on windows.

Upvotes: -2

Rehan Raees
Rehan Raees

Reputation: 1

I have resolve this issue.

May you are using old version of reactjs, Don't need to update that. Just do following:

  • Copy jsx-dev-runtime.js , jsx-runtime and cjs folder from the lastest react (lastest) present in node_modules

  • Paste these in react folder present in node_modules where the error occur.

Let me know it work or not!

Thank you!

Upvotes: -3

Oliver
Oliver

Reputation: 170

This did it for me!

rm -rf node_modules package-lock.json && npm i 

Upvotes: 11

Ayushi Garg
Ayushi Garg

Reputation: 1

Just upgrade the version of your react application. Check the version of react and typescript .Even I was facing same issue .When I upgraded to latest version my application was not showing any error.

For more information check the given link. https://betterprogramming.pub/upgrade-create-react-app-based-projects-to-version-4-cra-4-d7962aee11a6

Upvotes: -2

Tyler
Tyler

Reputation: 986

For me, I was missing .js in my webpack config's resolve.extensions.

I know OP is using rollup but for webpack users running into the same issue. :)

I'm currently doing a project with typescript, react, webpack and babel-loader.

I didn't have any source js files so I thought do I really need .js in the resolve.extensions array in my webpack config?

Then I started encountering the error:

Module not found: Error: Can't resolve 'react/jsx-runtime' in '/home/tylerbreau/repos/portfolio/src/views/app' @ ./src/views/index.tsx 4:0-53 7:30-41

I ended looking at the react folder in my node_modules and saw that it does have a jsx-runtime.js file. I tried adding it the .js back to webpack's resolve.extensions and the error disappeared.

In hindsight I guess this make senses.

Upvotes: 0

Moctar Yonli
Moctar Yonli

Reputation: 157

Updating your react version possibily can resolve your problem. Command line: npm install --save react@latest.

If you wish to specific a version, you need to run: npm install --save react@ e.g. npm install --save [email protected]

Upvotes: 1

Eliav Louski
Eliav Louski

Reputation: 5214

for me it was just an issue because I'm using Linux subsystem for windows with pnpm.

so in my node_modules/.modules.yaml i needed to change

#storeDir: /mnt/d/.pnpm-store/v3 # from this
storeDir: D:\.pnpm-store\v3 # to this

I think webstorm\vs code should understand both of them... but I am too last to open an issue for this.

update: actually, this does not always work, just use normal windows terminal when installing with pnpm

Upvotes: -1

Luan Miranda
Luan Miranda

Reputation: 45

yarn add [email protected]

Upvotes: -7

Taran
Taran

Reputation: 14126

I had a similar error and the problem was that I had forgotten to run npm install

Upvotes: 14

Charklewis
Charklewis

Reputation: 5631

So my setup actually was working. There was somehow a glitch in the symlink. I as able to resolve by running yarn unlink and yarn link. The package is now bundling correctly.

Upvotes: 6

Related Questions