[quickjs-devel] Re: Newbie: Getting something like require to work?

  • From: Juan C <juancampa@xxxxxxxxx>
  • To: quickjs-devel@xxxxxxxxxxxxx
  • Date: Tue, 13 Apr 2021 16:56:09 -0400

Most of the Node.js API can be shimmed. For example:

 - `querystring`: https://github.com/mike-spainhower/querystring
 - `path`: https://github.com/browserify/path-browserify

An easy way to get `require`/`import` working with node.js built-ins,
regardless of the runtime (quickjs included), is to pass your code through
a bundler first (like rollup). Think about it, the point of browserify was
to "be able to run node.js code on the browser", where "require" and
"import" weren't available. I guess what I'm trying to say is that this is
a solved problem, you just have to see how they are doing it.

Hope this helps,
Juan

On Tue, Apr 13, 2021 at 9:27 AM ShaJunxing <shajunxing@xxxxxxx> wrote:

在 2021/4/13 下午12:42, David Creelman 写道:

Hi,
I'm wanting to use some code that has things like...

var fs = require("fs");var nodePath = require("path");


Is there some way to simulate/emulate/add something to get require to work?

I wonder/imagine that the needed scripts could be loaded via -I or
--include, but I'm not sure how to use the loaded script once I've included
it...

How does something using nodepath....

remotePath = nodePath.resolve(process.cwd(), remotePath);


work?


I believe it can be done by writing a require() function following
commonjs and node.js module rules (http://wiki.commonjs.org/wiki/Modules
https://nodejs.org/dist/latest-v14.x/docs/api/modules.html). I wrote a
simple one (
https://github.com/shajunxing/quickjs-misc/blob/main/require.js) which
can successfully load parse5 but others I tried failed with lots of errors,
I'm too lazy to improve it but I think it can be finished.

Other related posts: