首页 > 解决方案 > Cant import React

问题描述

I started learning about React and i have problem with importing the library. Take a look at my code.

This is my HTML named index.html:

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>

<body>
    <div id="root"></div>
    
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="script.js"></script>
</body>

</html>

And this is my JS named script.js:

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

ReactDOM.render(<h1> Hellow World </h1>, document.getElementById("Root"))

And thats the error i get when im opening the index file:

Cannot GET /ReactDOM%20%5E&%20JSX/index.html

I imported those 2 scripts from React site.

标签: javascriptreactjs

解决方案


You need to spin up a server running on localhost, that can serve the files. Right now a GET request to your localhost does not work, because there is no server running that hosts the files. You only opened the file with your browser.

Check out create react app to get started with a good setup.

If you want to manually serve files. Check out the serve package. You can quickly test this by running

npx serve folder-name

推荐阅读