Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - "Uncaught ReferenceError: require is not defined" when importing into App.js for React App created using CDN links

I have created a React App that renders and h1 tag with "Hello World" to the browser. I have setup the App using CDN links rather than npm. The App has three files:

  1. index.html with one div tag with id of "root"
  2. App.js which renders my jsx to the div tag called root
  3. styles.css which I intent to use for some styles

Now the challenge is when I add import './styles.css' at the top of my App.js, the App breaks and nothing appears on the browser. Upon inspecting the browser console I find the error message:

"App.js:1 Uncaught ReferenceError: require is not defined"- Here is the screenshot of the error message from the browser console

My question is how do I import scripts/ other react components into my App.js without getting this error message? Why is babel giving me this error?

Here are the index.html, style.css and App.js codes:

class App extends React.Component{
  render(){
    return(
    <div>
      <h1 className="heading">Hello World</h1>
    </div>)
  }
}

ReactDOM.render(<App/>, document.getElementById('root'))
.heading{
    display: flex;
    text-align: center;
    font-size: 30px;
    color: blueviolet;
}
<!DOCTYPE html>
<html>

<head>
    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <link rel="stylesheet" src="style.css">
    <script src='https://unpkg.com/[email protected]/umd/react.production.min.js'></script>
    <script src='https://unpkg.com/[email protected]/umd/react-dom.production.min.js'></script>
    <script src='https://unpkg.com/[email protected]/babel.js'></script>

</head>

<body>
    <div id="root"></div>
   
    <script src="App.js" type="text/babel">

    </script>
</body>

</html>
question from:https://stackoverflow.com/questions/65857916/uncaught-referenceerror-require-is-not-defined-when-importing-into-app-js-for

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

1 Reply

0 votes
by (71.8m points)

I finally found out that the easiest solution is to link into my index.html like so:

<link rel="stylesheet" href="styles.css">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...