R
R
RichardTrump2020-08-16 14:22:15
JavaScript
RichardTrump, 2020-08-16 14:22:15

How to fix broken import in client js file in html working in node.js w/o express server?

Hello! Such a thing, there is a default server on node js w/o express:

const express = require('express')

const app = express()

app.get('/', function(req, res) {
    res.sendFile(__dirname + 'index.html')
})

app.listen(8080, () => console.log('Server started!'))


If the user is on the default route /, I throw him index.html with a simple Html structure (because I did everything for the test and I don’t have any layouts there). The only thing I have in index.html is a script connected with this line:

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

Nothing unusual at all. The problem is the following: I have more add. file in ./libs/main.js, this is also a test file, but from it I export a function from the console with a welcome log, and in script.js I import this function from the main.js file and call it accordingly. But as a result, v8 swears with the following error: Uncaught SyntaxError: Cannot use import statement outside a module. Before that, there was a problem with Import recognition in general, I solved it with the help of babel-cli, babel-preset-env, it's like transpiring to es6, because node js does not support this syntax. Which was also the problem. I tried many options, both through require, and through type="module", and through many more things. Now I even thought of using webpack, but I still want to solve this problem.

Thank you for your time!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kocherman, 2020-08-16
@RichardTrump

function require(url,cb){
  let script = document.createElement('script');
  script.setAttribute('type','application/javascript');
  script.setAttribute('src',url);
  if('function' == typeof cb) 
    script.addEventListener('load', cb, false);
  document.head.appendChild(script);
  return script;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question