require is not defined

a 夏天 提交于 2019-12-28 03:42:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/36698354/require-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!