Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function Import not working

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());
like image 890
s.n Avatar asked Jan 15 '17 14:01

s.n


People also ask

Does import work in JavaScript?

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!

What is a dynamic import ()?

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.

Should I use import or require?

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 .


1 Answers

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

like image 172
NotBad4U Avatar answered Oct 03 '22 22:10

NotBad4U