Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES module import not working

Tags:

javascript

I am trying to make simple example of vanilla ES import export.

index.js

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <script type="module" src="main.js"></script>
</head>
<body>

</body>
</html>

main.js

import {foo} from './mathModule';

console.log(foo);

mathModule.js

export const foo = Math.sqrt(2);

when I run this page I get an error

main.js:1 GET http://[page].net/test/mathModule 404 (Not Found)

EDIT: project structure

  • test
    • index.html
    • main.js
    • mathModule.js
like image 637
tprieboj Avatar asked Mar 06 '23 19:03

tprieboj


1 Answers

import needs a fully qualified URL. You can't leave off the extension unless the absolute URL doesn't have an extension on it.

So judging by your examples use:

import {foo} from './mathModule.js';

As Nimeshka Srimal caught, it looks like the extension requirement varies between implementations. Firefox is appending .js automatically, but Chrome and Safari expect the actual address.

I'm looking at the spec, 15.2.2 Imports, and there doesn't seem to be any specification on whether the implementer should append the extension automatically or not.

Additionally, as ASDFGerte pointed out from the MDN docs on import:

The module to import from. This is often a relative or absolute path name to the .js file containing the module. Certain bundlers may permit or require the use of the extension; check your environment. Only single quotes and double quotes Strings are allowed.

like image 125
zero298 Avatar answered Mar 20 '23 19:03

zero298