I am trying to understand modules in JavaScript but when I try to write a very simple module I get CORS error.I am using bracket as my text editor and the odd part is when I'm using live preview in brackets the code works but when I normally open the .js
file I get error.
index.html
<!DOCTYPE html> <html> <head> <title> JS </title> </head> <body> <script type="module"> import {add} from './libA.js'; console.log(add(10,20)); </script> </body> </html>
libA.js
export function add(a,b) { return a+b ; }
*I get this error ->
Access to Script at 'file:///F:/WEB%20DEV/JavaScript/libA.js' from origin `null` has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.
(I even tried the latest version of chrome too)
A module in JavaScript is just a file containing related code. In JavaScript, we use the import and export keywords to share and receive functionalities respectively across different modules. The export keyword is used to make a variable, function, class or object accessible to other modules.
JavaScript modules allow you to break up your code into separate files. This makes it easier to maintain the code-base. JavaScript modules rely on the import and export statements.
A module is nothing more than a chunk of JavaScript code written in a file. By default, variables and functions of a module are not available for use. Variables and functions within a module should be exported so that they can be accessed from within other files. Modules in ES6 work only in strict mode.
Introduction to the JavaScript import()The import() allows you to dynamically import a module when needed. Here is how the import() works: The import() accepts a module specifier ( moduleSpecifier ) that has the same format as the module specifier used for the import statement.
Many browsers do not allow you to access files on the local filesystem with JavaScript (even if the HTML document is also on the local filesystem).
This extends to loading JavaScript modules.
Install a webserver and use that (with a URL like http://localhost/
) for testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With