Sk_Joat
Sk_Joat

Reputation: 133

'import' statement not working in script in rendered HTML

I'm developing a express application and Im trying to do the below thing and I keep getting the same error over and over - "GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)"

Could someone please point out to me what mistake I am committing and point me in the right direction? Below is my code -

Module1.js

import theFunc from "./module2";
console.log("In module 1");
theFunc();    

Module2.js

export default function theFunc() {
console.log("from module 2");
}

index.html

<html>
 <body>
   Should show the result in console.
  <script type="module" src="./javascript/module1.js"></script>
 </body>
</html>

Thanks a ton in advance! :)

Upvotes: 12

Views: 13165

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161457

The message points out the issue, but it's still pretty easy to miss.

GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404

is the issue, because instead of

http://localhost:3000/javascript/module2

the URL is actually

http://localhost:3000/javascript/module2.js

with a .js extension.

The issue is that

import theFunc from "./module2";

should be

import theFunc from "./module2.js";

Upvotes: 40

Melchia
Melchia

Reputation: 24244

The import and export statements belong to ES6 therfore you need to use a transpiler like Babel. You second option is to use require which the equivalent in ES5:

First add this script to the head of your html:

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
</head>
<body>

Change these lines:

import theFunc from "./module2";

becomes

 var theFunc = require("./module2");

& this one too:

export default function theFunc() {
console.log("from module 2");
}

becomes:

function theFunc() {
console.log("from module 2");
}
module.exports = theFunc;

Upvotes: 1

Related Questions