2

I am writing an app in Reactjs using react CDN Links, not 'npx create-react-app'. I have created an index.html, index.js, and App.js files. I want to import the App.js component in Index.js file using import App from '../components/App.js' but it is giving "can not use import statement outside module" error on the browser (client-side). following are the codes

INDEX.HTML

<!DOCTYPE html>
<html>
<head>
    <title>Notepad Web App</title>
</head>
<body>
    <div id="root"></div>

    <!-- React CDN -->
    <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>

    <!-- JSX -->
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>


    <!-- External JS File -->
    <script type="text/javascript" src="./index.js"></script>
</body>
</html>

INDEX.JS

import App from '../components/App.js'
const e = React.createElemnt;
ReactDOM.render(e(App), document.querySelector('#root'));

APP.JS

const e = React.createElement;

function App()
{
    return(
        e("h1",{},'This is React App')
    )
}


export default App;
Hamada
  • 1,836
  • 3
  • 13
  • 27
Zain Ul Abideen
  • 389
  • 7
  • 25

2 Answers2

2

To include a JavaScript module in an HTML page, you have to tell that to the browser explicitly by adding type="module":

<script type="text/javascript" type="module" src="./index.js"></script>

You can read more about modules and how to use them here.

EDIT:

Regarding the new error you get, see here:

Unlike regular scripts, ES6 modules are subject to same-origin policy. This means that you cannot import them from the file system or cross-origin without a CORS header (which cannot be set for local files).

Basically you need to run this code from a (local) server.

You can use live-server:

  1. Install it by running:
npm install -g live-server
  1. Run in your website folder:
live-server
  1. Open http://localhost:8080 in your browser, and your site will work
assembly_wizard
  • 2,034
  • 1
  • 17
  • 10
  • By applying the changes suggested by you, now I am facing following error on browser. ` Access to script at 'file:///home/ubuntu/Desktop/projects/notepad/public/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.` – Zain Ul Abideen Jul 05 '20 at 04:29
1

Changing the type to"module" can solve the issue like this:

<script type="module" src="./index.js"></script>

Also, you have a syntax error line 2 in index.js const e = React.createElemnt; you have a missing e in the word Elemnt.

Nasser Abachi
  • 1,308
  • 1
  • 9
  • 12