11

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());
8
  • Try to use './two' Commented Jan 15, 2017 at 14:10
  • Can you see in the console any errors messages with the import statement? Commented Jan 15, 2017 at 14:11
  • @MustafaMamun content of the two.js is given above Commented Jan 15, 2017 at 14:11
  • Sorry have not seen it before corrected it. Commented Jan 15, 2017 at 14:13
  • 3
    ES6 modules aren't supported in browsers (with the exception of Edge). The code needs to be transpiled with Babel. Commented Jan 15, 2017 at 14:25

1 Answer 1

20

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

Sign up to request clarification or add additional context in comments.

4 Comments

ES6 modules have got experimental support in Edge developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
All modern browsers now support JavaScript modules via script tag
"You need to use a transpiler like Babel" — Babel is not a bundler. It can translate one module syntax into another, but it won't combine modules into a single script. Since browsers do support import and don't support require, using Babel is unhelpful (unless used in combination with a bundler).
This response is now out of date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.