Pangit
Pangit

Reputation: 664

JS module throwing error upon declaration

I have a webpage (.ejs) that calls a separate file to contain the necessary JS, as here:

<html lang="en">
  <head>

  //stuff

  </head>
  <body>

  //stuff

  <script type="module" src="/public/js/p2p_logic.js"></script>                            
  
  </body>
</html>

With the corresponding JS as here:

//p2p_logic.js

addEventListener("load", connect);
addEventListener("load", initialize);

//stuff

function connect() {
console.log("FIRED CONNECT");    
}  //connect()

function initialize() {
console.log("FIRED INITIALIZE");
import WebRTCAdaptor from "./public/js/webrtc_adaptor.js"        
}  //initialize()

As can be seen, the JS file calls an 'import'. I am having great difficulty getting this to be operative. I have never used an 'import' within a JS script file (attached to an HTML/EJS page) before. As written above, I am receiving this error:

Uncaught SyntaxError: Unexpected identifier  p2p_logic.js:27 

I have also attempted to use 'curly' brackets, as here:

import {WebRTCAdaptor} from "./public/js/webrtc_adaptor.js"

However this seems to have no effect. If I modify the JS file to 'import' on the initial line, as here:

//p2p_logic.js

import WebRTCAdaptor from "./public/js/webrtc_adaptor.js"   

addEventListener("load", connect);
addEventListener("load", initialize);

//stuff

function connect() {
console.log("FIRED CONNECT");    
}  //connect()

function initialize() {
console.log("FIRED INITIALIZE");
}  //initialize()

This throws a 404 error...which indicates a 'file not found'. Specifically:

Failed to load resource: the server responded with a status of 404 ()  webrtc_adaptor.js:1

That however is BS since the file is definitely in the './public/js' directory...the 'webrtc_adapter.js' file is in the same directory as the 'p2p_logic.js' file...but I am using an absolute path structure so I don't see how that would matter...?

I am beginning to think it is not possible to perform an 'import' of a file in this manner...I have never had an issue using an external JS file in conjunction with a HTML/EJS page before...however in those cases I never made usage of an 'import' statement.

Does anybody know if it is even possible to 'import' using an external JS file attached to a HTML/EJS page?

Upvotes: 0

Views: 301

Answers (2)

Pangit
Pangit

Reputation: 664

I have the 'import' problem now resolved...I had included a period (".") within the path that should not have been there...which is why I was seeing a 404 error being thrown. The correct 'import' path should have been '/public/js/...' instead of './public/js/...' Thanks again to those that responded.

Upvotes: 0

TiltedToast
TiltedToast

Reputation: 21

You have script tags inside your .js file which is throwing an error because those are html and you can't have that in a JavaScript file. Remove those and you should be good

Upvotes: 1

Related Questions