1

I was trying to run some NodeJS code using QickJS and NectarJS, and I stumble in an old question I have, how to import modules.

In special, qjs -m <source-js> loads ES6 modules, and expect import export statements,, instead of require, and writing module.exports, or exports.

Also I use an builtin std module (that cannot be resolved by node_module).

For the first example I changed the code manually, but I would like to have a script to do the transformations. I expected this to be doable with webpack, but I can't find how.

Example

main.js

const h = require('./hello.js');
h.sayHello();

hello.js

const h = require('./print.js');
function sayHello(){
  h.print("Hello");
}
module.exports = {sayHello};

print.js

module.exports = {
  print(s) {
    console.log(s);
  }
}

I can run this with the command node main.js, but qjs -m main.js, will fail with 'require' is not defined

Bob
  • 13,867
  • 1
  • 5
  • 27

1 Answers1

0

QuickJS does not support CommonJS-modules. Instead it supports native JS-Modules following the ECMA-standard. So you either

  1. transpile from CommonJS into std-modules and then use import/export instead of require. As you mentioned webpack, that'll do fine. ESBuild can transpile from CommonJS(.cjs) to ES-Module(.mjs) too. Or
  2. you might try the require-loader for QuickJS - which i found here https://github.com/IvanGaravito/quickjs-require.

regards, Andreas

Bosinski
  • 1
  • 1
  • 1
    Welcome Andreas. Your answer is not complete. You mentioned a few solutions, now can you show the steps to apply them to the example I gave. – Bob Mar 01 '23 at 13:24