79300078

Date: 2024-12-21 20:47:21
Score: 0.5
Natty:
Report link

Ended up using res.sendFile() to serve the js file and module language to import it into my client-side script. Did not see this particular solution anywhere, but works like a charm. Note if you're coming at this from scratch, the other adjustment was to add "type": "module" to package.json to get ES6 modules working.

in app.js:

express.static(`./project/public`)(req, res, next);
app.use(`/project`, `./project/index.js`);    
app.get('/utilities.js', function(req, res) {
    res.sendFile(`${path.resolve('./','utilities')}/utilities.js`);
});

in html:

<script type="importmap">
    {
       "imports": {
       "u": "/clientutilities.js"
    }
}
</script>
<script type="module" src="script.js"></script>

in script.js:

import wow from 'u';
alert(wow.woo());

in utilities.js:

function woo() {
    return "woo";
}
export default { woo };

Loading the page alerts "woo". Looking forward to building a portable single server-side file of client-side js functions.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Michael VanLaanen