0

I am just trying to have fun with JS, I am creating a small project trying to implement a new architecture that I di not use before, I was always using js in React apps, or using native JS but not creating an app with it, I was using it to create some animations and handle some changes in my pages, nothing complex).

I want to learn how to create a JS app, implementing a MVC architecture ! I am not following any tutorial, so here is my folder structure :

enter image description here

Here is my index.html :

<html>
    <head>
        <title>Test js PROJECT</title>
    </head>
    
    <body>
        <div id="root"></div>
        <script src="app.js"></script>
    </body>
</html>

And that's my app.js :

import { loadApp } from './MVC/controllers/loadApp';

loadApp();

And that's is my loadApp.js :

const loadApp = () => {
    const showUsersOption = document.createElement('button');
    const showProductsOption = document.createElement('button');
    
    showUsersOption.createTextNode('Users');
    showProductsOption.createTextNode('Products');

    const app = document.getElementById('root');

    app.appendChild(showUsersOption);
    app.appendChild(showProductsOption);
}

export default loadApp;

So I think what I am trying to do is simple, adding two buttons to the root element, But I got this :

app.js:1 Uncaught SyntaxError: Cannot use import statement outside a module

Based on this comment to the question, I added type module in my script like that :

<html>
    <head>
        <title>Test js PROJECT</title>
    </head>
    
    <body>
        <div id="root"></div>
        <script type="module" src="app.js"></script>
    </body>
</html>

But I got this :

Access to script at 'file:///C:/Users/Taoufiq.BENALLAH/Desktop/Master/js/app.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

GET file:///C:/Users/Taoufiq.BENALLAH/Desktop/Master/js/app.js net::ERR_FAILED

Based on the comments in this question here, I have to restart my editor or run npm install, but I am not using node modules or anything, my app is simpler than that.

Any idea ? Any help would be much appreciated.

TaouBen
  • 1,165
  • 1
  • 15
  • 41
  • 2
    You need to run your app on a server(local or remote). Its a security issue to load files from the client filesystem for reading without user interaction, so loading from `file:///` generates an error – Patrick Evans Dec 10 '20 at 10:13
  • 1
    You need to serve your script in an http server, browsers use an http request to load es6 modules, the server needs to respond in the header a CORS allowing your origin – Samse Dec 10 '20 at 10:15
  • So I have to use npm and run my app ? – TaouBen Dec 10 '20 at 10:18
  • 1
    Either serve your files with a npm server or use a local servel like xampp or mamp – Samse Dec 10 '20 at 10:19

0 Answers0