I am trying to import a function from a separate .js file. When I declare the import command the page is not executing the code. But when I delete the import command and execute a simple alert('Hello'), that thing is popping up on the page.
PROJECT STRUCTURE
--Todo-app
----js
------two.js
------main.js
----index.html
Index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="js/main.js"></script>
</body>
</html>
two.js
export function one() {
return 1 + 1;
}
main.js
import { one } from 'two';
alert(one());
In js import works in a way that the imported modules are invoked first wherever you place your import statements in your file and after that your current file is executed. That's how js works!
The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .
The import and export statements is not implemented in any browsers natively at this time. You need to use a transpiler like Babel
But chrome and firefox can parse this statements Uncaught SyntaxError: Unexpected token import
but not support the module loading.
See MDN for more détails Reference Statements import
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