Cannot find module 'react'
Asked Answered
G

11

37

I'm attempting to integrate React into an existing web page. At this time, I'm unable to get my React app loaded. My React app has two files. At this time, they look like this:

myApp.js

import React from 'react';
import ReactDOM from 'react-dom';

import MyComponent from './components/myComponent';

ReactDOM.render(<MyComponent />, document.getElementById('root'));

myComponent.js

import React from 'react';
import ReactDOM from 'react-dom';

class MyComponent extends React.Component {
  render() {
    console.log('here');
    return (
      <div>
        <h2>Hello (from React)</h2>
        <br />          
      </div>
    );
  }
}

export default MyComponent;

As you can see, I'm using ES6. I'm determined to use ES6 on this project. For that reason, I'm using Babel in my Gulp file to bundle my React app. I'm using Gulp instead of Webpack because my site is already using Gulp. Still, the relevant details in my package.json file look like this:

package.json

...
"devDependencies": {
  "babel-preset-es2015": "^6.14.0",
  "babel-preset-react": "^6.11.1",
  "babelify": "^7.3.0",
  "browserify": "^13.1.0",
  "gulp": "^3.9.1",
  "gulp-babel": "^6.1.2",
  "gulp-clean-css": "^2.0.11",
  "gulp-uglify": "^1.5.4",
  "vinyl-source-stream": "^1.1.0"
}

I then bundle my React app using the following task:

gulpfile.js

gulp.task('buildApp', function() {
    return browserify({ entries: ['./app/myApp.js', './app/components/myComponent.js'] })
        .transform("babelify", {presets: ['es2015', 'react']})
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./app'))        
    ;
});

When the above task is ran, the bundle.js file gets generated. It looks like this:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _myComponent = require('./components/myComponent');

var _myComponent2 = _interopRequireDefault(_myComponent);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

_reactDom2.default.render(_react2.default.createElement(NyComponent, null), document.getElementById('root'));

},{"./components/myComponent":2,"react":"react","react-dom":"react-dom"}],2:[function(require,module,exports){
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MyComponent = function (_React$Component) {
  _inherits(MyComponent, _React$Component);

  function MyComponent() {
    _classCallCheck(this, MyComponent);

    return _possibleConstructorReturn(this, (MyComponent.__proto__ || Object.getPrototypeOf(MyComponent)).apply(this, arguments));
  }

  _createClass(MyComponent, [{
    key: 'render',
    value: function render() {
      console.log('here');
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'h2',
          null,
          'Hello (from React)'
        ),
        _react2.default.createElement('br', null)
      );
    }
  }]);

  return MyComponent;
}(_react2.default.Component);

exports.default = MyComponent;

},{"react":"react","react-dom":"react-dom"}]},{},[1]);

Then, in the web page that I'm trying to load this app into, I have the following:

...
<div id="root"></div>

<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script type="text/javascript" src="/app/bundle.js"></script>
...

When I load attempt to load this in the browser, my React app does not load. I can see in the console window the following error message:

Uncaught Error: Cannot find module 'react'

I don't understand why react isn't getting loaded.

Greenfinch answered 18/9, 2016 at 13:12 Comment(1)
@AndrewL. - This code sample was. However, my actual code has it typed correctly. Mistake in formatting on my part. I've fixed the question. Thank you for pointing this out.Greenfinch
C
23

Your package.json doesn't have React in it. It's pretty hard for your project to use a package you haven't installed.

Just add: "react": "^15.3.1" to your package.json and do a new npm install, and you should be fine.

Carousal answered 18/9, 2016 at 16:50 Comment(2)
Is it the same error, or is it now complaining about ReactDom (which is also missing in your package.json)?Carousal
Also double check that you don't have multiple package.json files in different directories. If so, they each must have react specified.Promotive
S
35

You are planning to use react inside typescript. Try this

npm install --save react react-dom @types/react @types/react-dom
Sourdough answered 26/2, 2019 at 4:34 Comment(0)
C
23

Your package.json doesn't have React in it. It's pretty hard for your project to use a package you haven't installed.

Just add: "react": "^15.3.1" to your package.json and do a new npm install, and you should be fine.

Carousal answered 18/9, 2016 at 16:50 Comment(2)
Is it the same error, or is it now complaining about ReactDom (which is also missing in your package.json)?Carousal
Also double check that you don't have multiple package.json files in different directories. If so, they each must have react specified.Promotive
C
11

Do npm install react in your local directory. It worked for me.

Consternation answered 19/3, 2017 at 11:28 Comment(0)
Q
5

I am using Gatsby and React was in my package.json with the following:

"react": "^16.7.0",
"react-dom": "^16.7.0",

It was previously working when I ran gatsby develop. However, when I installed a couple of plugins (npm install --save less gatsby-plugin-less), the "Error: Cannot find module 'react'" started popping up whenever whenever I did gatsby develop.

Weirdly, I just did npm install on the package.json folder and it fixed the issue.

Quagmire answered 27/3, 2019 at 10:26 Comment(0)
T
1

I Was facing this issue and in my case, I was referring a .env file and it was missing from my repo. Bring back the file and it works. Make sure to check these types of files that you are using in your project. There is no clear error message.

Triptych answered 18/5, 2020 at 12:58 Comment(0)
T
0

There was another package.json file in the parent directory of the project which was causing this issue. Once I deleted those and reinstalled packages, it worked fine for me.

Tevet answered 15/9, 2022 at 6:18 Comment(0)
L
0
import React from 'react'

Type the above again after deleting and don't let it auto import ie, type it fully. I know this seems naive but it worked for me several times. It has something to do with ide.

Lilly answered 25/3, 2023 at 14:46 Comment(0)
M
0

the technical answer would be to run

npm install --save react react-dom / yarn add react react-dom

but if you just ran create-react-app those should have been installed automatically and something probably went wrong. Try and follow these steps as close as possible.

npx create-react-app my-app
cd my-app
npm start

If you've previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app or yarn global remove create-react-app to ensure that npx always uses the latest version.

Miseno answered 5/6, 2023 at 18:42 Comment(0)
G
0

I guess you forgot about babel require in your myApp.js

const React = require('react');
Gardia answered 7/8, 2023 at 10:58 Comment(0)
D
0

I was also getting the same type of error while using Parcel and React. I deleted the .parcel-cache and dist folder and started the build process again. It worked for me.

Dermatoid answered 3/1 at 3:39 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Phonogram
J
-1

yarn add react react-redux that fixed it for me

Juanjuana answered 17/8, 2022 at 11:9 Comment(1)
React and react-redux are different.Scarlett

© 2022 - 2024 — McMap. All rights reserved.