1

Just started learning React, and I'm getting

ReferenceError: require is not defined 
<anonymous>http://localhost:3000/js/script.js:3:5

in console log.

Here's my JSX:

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

const element = <h2>Testing</h2>;
ReactDOM.render(element, document.getElementById("test"));

JS

"use strict";

var _react = _interopRequireDefault(require("react"));

var _reactDom = _interopRequireDefault(require("react-dom"));

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

var element = _react.default.createElement("h2", null, "Testing");

_reactDom.default.render(element, document.getElementById("test"));

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Your title</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="../css/style.css">
</head>

<body>
    <section id="content">
        <section id="test"></section>
    <script src="/js/script.js"></script>
</body>

</html>

I've got Babel and Gulp running and the background, and they are working properly. I noticed that when I add React CDN the problem is gone, after removing the following from my JSX file.

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

I didn't use npx create-react-app my-app command since this is a project I was already working on, instead I just installed Babel, configured it, added it to Gulp, installed react, react-dom, and react-scripts.

Here's my directory structure:

|   .babelrc
|   .gitignore
|   .pug-lintrc.json
|   .sass-lint.yml
|   gulpfile.js
|   package-lock.json
|   package.json
|   
||||css
|       style.css
|       
||||html
|       index.html
|       
||||js
|       script.js
|       
||||jsx
|       script.jsx
|       
||||node_modules

It's no problem for me to use the CDN, but I just want to know what I'm doing wrong here. I'm guessing that I'm not properly importing React from 'react' but I can't pinpoint the cause.

Mentalhead
  • 1,501
  • 5
  • 20
  • 28
  • 1
    I imagine it's because `require` is a node thing and this is on the browser? You could import it as you do in the JSX file, then run it through the interop function. – Jonny Rathbone Feb 23 '19 at 10:30

2 Answers2

1

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code. Compatible with almost all latest browsers.

Add this to your project

Then, have a look at this.

0

Bhojendra Rauniyar and Jonny Rathbone pointed me in the right direction. Require is part of Node.JS and it's not natively supported in your browser.

To enable it, you need to use one of the options mentioned here: Client on node: Uncaught ReferenceError: require is not defined

I went for Browserify, but using a CDN is also an option.

Mentalhead
  • 1,501
  • 5
  • 20
  • 28