mozilla / rhino

Rhino is an open-source implementation of JavaScript written entirely in Java
https://rhino.github.io
Other
4.17k stars 846 forks source link

[CommonJS] Support for loading (nodejs) packages #55

Open facundocabrera opened 12 years ago

facundocabrera commented 12 years ago

Hello,

I'm trying to load a module's folder instead of a specific js file and I'm getting a error:

ReferenceError: "index" is not defined. (file:/****/modules/test#1).

  1. The root of the modules is configured to be: file:/****/modules/
  2. From a script (modules.js) I'm doing:

    var test = require("test");

    Where, test in a folder inside modules with an index.js file defining the module's startup.

Important:

If I define the require as:

    var test = require("test/index");

The code works perfect.

My Findings:

I'm using the class UrlModuleSourceProvider, and I guess I could check if the moduleId is a
directory, and then append the string "/index" to the moduleId in that situation, but I'm not 
sure if that is the best way to add the behaviour.

Could someone give me a hand?

Thanks!

hns commented 12 years ago

Loading packages currently isn't supported by Rhino's CommonJS module loader. Strictly speaking, package support is not part of the CommonJS module spec. I'll see if I can port the relevant bits from RingoJS to add package support to Rhino.

facundocabrera commented 12 years ago

For now I've extended the class UrlModuleSourceProvider and added the loading behavior without problem. My idea is reuse packages via npm parsing the package.json in a near future.

BTW, Yesterday I tested part of the Jade template engine inside Google App Engine without major problems :D

Thanks for your great work!

hegemonic commented 12 years ago

I also got this working by extending UrlModuleSourceProvider. The subclass I came up with is here: https://github.com/hegemonic/rhino/blob/f2232b/src/org/jsdoc/JsDocModuleProvider.java

Anyone who wants to fold my code into Rhino is welcome to do so! I'm sure there's room to improve it, since I hardly ever code in Java...

p-bakker commented 1 year ago

As @hns mentioned, loading (nodejs) packages isn't part of the CommonJS specification and thus not part of Rhino's CommonJS implementation, thus I marked this as a Feature

If packages support is required right now, either use https://github.com/micmath/Rhino-Require or fiddle with the (Url)ModuleSourceProvider as suggested in https://github.com/mozilla/rhino/issues/55#issuecomment-9448205 to achieve the result you want.

As (nodejs) package isn't standard CommonJS, I would not expect this to become part of the Rhino core, but maybe some add-on that can be pulled into your environment if needed

Also tagged this with the docs tag to make a note about this in the documentation