简体   繁体   中英

"require is not defined" when I import something from node_modules

I am building a simple Blog App in React, I am newbie React and I am using Routing, so I have to import Route from react-router-dom , But when I import it like

import { Route } from "react-router-dom";

then it is showing

Uncaught ReferenceError: require is not defined

it happens in every file, I try to import in App.js.

I created a new folder named js in public folder where the App.js is located.

I have tried hours upon hours, But it is still showing that Error. I have also tried using browsify and webpack but still showing.

App.js

import { Route } from "react-router-dom";

function App() => {
    return (
        <div>
           React App
        </div>
    )
}

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

package.json

{
  "name": "my-react-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.3",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.26.0",
    "history": "^5.3.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "5.2.0",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "webpack": "^5.70.0"
  }
}

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>React-App</title>

    <script src="vendor/babel-standalone.js"></script>
    <script src="vendor/react.js"></script>
    
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="vendor/react-dom.js"></script>
    
  </head>
  
  <script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
  <body >
    <div id="content"></div>

    <script
      type="text/babel"
      data-plugins="transform-class-properties"
      src="App.js"
    ></script>
  </body>
</html>

Any help would be much Appreciated. Thank You in Advance.

I think your App.js should be in src folder and not in public . Try to move it and retry.

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