简体   繁体   中英

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

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')
);

You have to use

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

in place of

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

Consider to use ES6 modules instead of require with React

export a module:

// src/hello.js
// export as default
export default const hello = ({name}) => (
  <h1>Hello {name}</h1>
)

import a module:

// src/index.js
// import from relative directory (src)
import Hello from './hello'

const App = () => {
  return (
    <div>
      <Hello name="Pavel" />
    </div>
  )
}

You should read more about modules for example here: https://www.sitepoint.com/understanding-es6-modules/

The main problems in your existing code are:

  1. It looks, in spite of that you are using Webpack, you use it wrong way. In your final bundle (final JS file), it shouldn't contain any 'require' keywords. Did you use Babel with your webpack? Please, show us your WebPack config.
  2. Your AdminMenu file looks not like module. Your adminMenu file should contain 'export' keyword, after that you will be able to 'require' or 'import' it from other files.

Also, you can write questions in comments with Russian if it is more convenient for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM