user949300
user949300

Reputation: 15729

I can't get a basic ES6 Import to work

Sorry, but what basic dumb thing am I doing wrong? I'm following this example code. Do I need a special way of serving the code? (I'm using http-server)

Chrome complains about

Minimal code follows:

mini.js

import {doSomething2} from "mini2";
// import doSomething2 from "mini2";  also fails
// also tried ... from "./mini2"

function doSomething1(url, opts) {
   return "mini1 " + doSomething2(url);
}

mini2.js

export function doSomething2(url, opts) {
   return ("mini2 " + url);
}

mini.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset=utf-8>
    <title>Test</title>
    <script src="mini.js"></script>
</head>

<body onload="console.log(doSomething1('hi there'))">

<header>
</header>
<main>
<h1> Test </h1>     
</main>
</body>

</html>

Update: I'm not using any transpiler or bundler. Following @MohammedWaleed advice, if the .html file uses type = "module" and mini.js imports mini2.js with a detailed path, import {doSomething2} from './mini2.js';, things more or less work. I can run inline code from mini.js which calls mini2.js. The issue is that functions in mini.js, e.g. dosomething1(), seem to be invisible.

Update 2 @loganfsmyth comment works. Seems like if your script is of type "module", you must setup globals manually. Slightly awkward, but fine. To avoid polluting the window global space too much, probably best to use a property of window, here I just used "mini":

window.mini = {
  doSomething1 :function doSomething1(url) {
     return "mini " + doSomething2(url);
  }
  anotherFunction: blah blah...
}

Upvotes: 4

Views: 4015

Answers (1)

Mohammad Waleed
Mohammad Waleed

Reputation: 305

Have you tried

import {doSomething2} from "mini2.js";

as i noticed it is included in the files in the following link, either way you should check the link it'll help you

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Edit : i found this article on medium it'll help you

https://medium.com/dev-channel/es6-modules-in-chrome-canary-m60-ba588dfb8ab7

Upvotes: 1

Related Questions