Zain Ul Abideen
Zain Ul Abideen

Reputation: 459

Uncaught SyntaxError: Cannot use import statement outside a module using reactjs CDN Links

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;

Upvotes: 2

Views: 5187

Answers (2)

assembly_wizard
assembly_wizard

Reputation: 2064

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

Upvotes: 2

Nasser Abachi
Nasser Abachi

Reputation: 1496

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.

Upvotes: 1

Related Questions