0

I am Facing the problem of how to use import/export syntax in my scripts, but only on the client-side(Frontend). I want to add scripts to my HTML that will be rendered from Node.js.For example, I want to have multiple script.js that represent modules, and to be able to import/export and render properly. .I do understand that code needs to be compiled to ES6 but having a problem finding how to do it. Thanks in advance.

example from this link: Loading javascript file in node?

    var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');

http.createServer(function(req, res) {
    if (req.url === '/') {
        fs.readFile('./index.html', function(err, data) {
            if (err){
                throw err;
            }
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.write(data); 
            res.end();
            return;
        });
    } else if (req.url === '/script.js') {
        fs.readFile('./script.js', function (err, data) {
            if (err) { throw err; }
            res.writeHead(200, { 'Content-Type': 'text/javascript' });
            res.write(data);
            res.end();
            return;
        });
    }
}).listen(3000);

Edit: Already tried to install Babel in the same project, but facing the error : Uncaught SyntaxError: Cannot use import statement outside a module

Milos
  • 31
  • 1
  • 6
  • 2
    You need to provide a more concrete example of what you're trying to achieve. At the moment this question is too broad to answer. – Andy Jun 06 '21 at 17:38
  • Hi. What's stack you coding? Pure Javascript? Still we need more context to understand your stuck. – alfredo Jun 06 '21 at 17:41
  • The babel error is most likely because of the settings in the config file. Change them so you can use es6 < syntax. – Invizi Jun 06 '21 at 17:43
  • Hey guys, edited my main post now. Hopefully you can understand me better :) – Milos Jun 06 '21 at 17:47
  • Your `fs.readFile('./script.js', //...` must point to the transpiled file, and transpiling must be done before the server handles the request. – mbojko Jun 06 '21 at 17:55
  • @mbojko, that is the issue. I do understand that it has to point to it, but not sure how to transpile it on first place – Milos Jun 06 '21 at 18:04

0 Answers0