Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

reactjs - require is not defined

Im building a new React app but get the following error - "require is not defined"

hello-world.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="react/react.js"></script>
    <script src="react/react-dom.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> 
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel" src="hello-world.js">
  </body>
</html>

hello-world.js

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

import App from './App.jsx';

ReactDOM.render(
        <App />,
        document.getElementById('example')
      );

App.jsx

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            Hello World!!!
         </div>
      );
   }
}

export default App;

Im running this from my client and don't have any web server running.

I tried to include http://requirejs.org/docs/release/2.2.0/minified/require.js but it gives a totally different error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're trying to use a CommonJS module from within your browser. This will not work.

How are you using them? When you write import ... from ... in ES6 Babel will transpile these calls to a module definition called CommonJS and since CommonJS isn't around in the browser you'll get an undefined error from require().

Furthermore, you're also trying to load RequireJS which uses a different module definition pattern called AMD, Asynchronous Module Definition, and will not take care of the require calls for you. You can wrap them in RequireJS specific calls.

If you want to use CommonJS modules in your code base you need to first bundle them with either Browserify or webpack. The two tools will transform your require calls to some glue magic that you can use within the browser.

But in your specific case, if you remove the import calls and just let the browser take care of and attach the classes you've created to the window object your code should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...