Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Uncaught ReferenceError: require is not defined

I'm trying to use DRY in React JS. I'm trying to use the same HTML partial in different files

partial:

var AdminMenu = React.createClass({
 getInitialState: function() {
   return {};
 },
 render: function() {
   return (
     <h1>Menu</h1>
   );
 }
});

I'm requeiring it in another file:

require('./scripts/adminMenu.js');

ReactDOM.render(
 <AdminMenu/>,
 document.getElementById('content')
);

But I'm getting an error:

Uncaught ReferenceError: require is not defined

this scripts are included on html page like: <script type="text/babel" src="scripts/admin.js"></script>

I'm using webpack

like image 976
Pavel Babin Avatar asked Jul 06 '16 08:07

Pavel Babin


People also ask

How do you fix ReferenceError require is not defined?

To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.

How do you fix uncaught ReferenceError process is not defined in React?

To solve the "Uncaught ReferenceError: process is not defined" in React, open your terminal in your project's root directory and update the version of your react-scripts package by running npm install react-scripts@latest and re-install your dependencies if necessary.

Why require is not working in js?

This usually happens because your JavaScript environment doesn't understand how to handle the call to require() function you defined in your code. Here are some known causes for this error: Using require() in a browser without RequireJS. Using require() in Node.

How do you fix the error require is not defined in node JS?

You are using require in a Node. If that is set to module , ES6 modules will be enabled and you will run into the error mentioned above (specifically ReferenceError: require is not defined in ES module scope, you can use import instead ). Simply remove that entry and you will be able to use require .


2 Answers

If you are not using any module bundler like webpack or etc. You should assign you components to some javascript global object, because objects from .jsx are not put in global scope

So here is the solution (used window object here)

Defined module:

window.AdminMenu = React.createClass({
  getInitialState: function() {
    return {};
  },
  render: function() {
    return (
      <h1>Menu</h1>
    );
  }
});

Where you use it:

ReactDOM.render(
  <window.AdminMenu/>,
  document.getElementById('content')
);
like image 96
Sergey Belousov Avatar answered Oct 01 '22 03:10

Sergey Belousov


You have to use

const { Component } = React;
const { render } = ReactDOM;

in place of

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
like image 30
Bakul Gadara Avatar answered Oct 01 '22 03:10

Bakul Gadara