简体   繁体   中英

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?

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?

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 . eg: import { sqrRoot } from "./math_function.js"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM