Javascript file importing other js file not react and not node.js module errors

I’m new to Javascript. Although I’m learning React and have used node.js in tutorials this issue does not involve tools from either.

Environment: I’m running a real-time stack app that has an embedded C++ http server. I server up an html landing page, which imports a javascript with functions:

<script src="dist/js/WebPageClientLanding.js"></script> 

As is, when the landing page is served it is rendered and buttons onclick’s work fine and all is working as expected. During this I’m connecting to my server via websocket.
However, my next task is to split out several of the functions from WebPageClientLanding.js that are I consider reusable for other landing pages I plan to server for different applications. In particular, one that I want to split out is called “connectWebsocket”.

I moved that code out of WebPageClientLanding.js into dmfunctions.js:

function connectWebsocket(address, port) {
       ....
}

export { connectWebsocket }

I’ve tried numerous ways to import dmfunction.js into WebPageClientLanding.js:

WebPageClientLanding.js:

import { connectWebsocket } from "./dist/js/dmfunctions.js" ; // first line

But I keep getting error (in Firefox, developer tools)

 Uncaught SyntaxError: import declarations may only appear at top level of a module WebPageClientLanding.js:8:5

I’ve search web for this error but all seem to assume import is from html file or Node.js or React is involved. Answers seem to assume either ES6 Modules or JSCommon, but I don’t know how to put these into effect.

I’m a newbie when it comes to JS. Thanks for your help.

1 Like

try adding type: module to your package.json or use .mjs as the extension for WebPageClientLanding file

To find out more about this, read about the differences between how Node.js processes ESM vs CJS

Thanks for the response, but I want to make sure I haven’t confused you about my situation.

I’ve developed the WebPageClientLanding.js and dmfunctions.js outside, i.e. not using at all, any React or Node.js related tools or libraries. My sense is that either I can’t do what I want, i.e. front end js code importing other server available js exported code, or being a newbe I haven’t learned how to do this in pure js.

All my reading on www has led me to believe that Node.js and React related tools provide a way to do this but since my project does not use a builder or other related tools those techniques are not available.

I guess this question comes down to how does one import/export multiple js files without special tools?

Thx

I suggest putting your code in a repository in github and sharing the link to it so people can look at what you have done and let you know what may work.