Safwen Hafsawy
Safwen Hafsawy

Reputation: 59

Cannot use import statement outside a module(Vanilla Javascript)

when i tried to import a class from one js file to another i got this error

Uncaught SyntaxError: Cannot use import statement outside a module

when i added type="module" to my script tags i got this error

Access to script at 'file link' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

any help on how to fix the error ?

Upvotes: 1

Views: 2953

Answers (3)

Bravo Stack
Bravo Stack

Reputation: 161

First off, you have to include the type="module" attribute in your script tag.

Secondly, when using the import statement, don't leave out the file extension, in this case .js. e.g: import { sqrRoot } from "./math_function.js"

Upvotes: 1

Jason V. Castellano
Jason V. Castellano

Reputation: 316

Just run your application by using your http server. Do not access it directly.

Upvotes: 0

Safwen Hafsawy
Safwen Hafsawy

Reputation: 59

this was simply solved by adding type="module" to my script tags and serving my web files from an HTTP server running on localhost instead of opening the html file directly

these answers were helpful :

How to run html file on localhost?

Upvotes: 3

Related Questions