How to include dependencies in J2V8

2.6k views Asked by At

How to include dependencies in J2V8? I would like to use certain dependencies in the javascript file for instance the crypto package.

var crypto = require('crypto');

function foo(){ return crypto.createHash('md5').update('Apple').digest("hex");}

However, I got the following error saying require keyword is undefined.

undefined:1: ReferenceError: require is not defined

var crypto = require('crypto');
         ^
 ReferenceError: require is not defined at <anonymous>:1:14
  com.eclipsesource.v8.V8ScriptExecutionException
at com.eclipsesource.v8.V8._executeVoidScript(Native Method)

Can anyone tell me how to import an package into J2V8?

3

There are 3 answers

0
user835611 On

Unless you're working with Node, require is not a feature. Usually, you want to use a bundler like webpack to pack your structured source code into one large file so that it can be understood by browsers. This way you can use require and npm packages for your frontend code, which makes development easier, and a bundler turns it with every build (or live update) into a different format, that's hard to read for humans, but is valid Javascript.

0
Raj On

I have had success using node modules in J2v8, please check out this blog :http://eclipsesource.com/blogs/2016/07/20/running-node-js-on-the-jvm/

NodeJs nodeJS = NodeJs.createNodeJs();

After registering callbacks

nodeJs.exec(File thescripttoexecute)

Make sure you have the proper path to the node modules in the require() command.

0
jeeeyul On

You may have to make a nodejs package that takes dependencies and exports what you need. Then, You have to execute npm install manually.

or You can just npm install what-you-need.

Create Node JS Runtime, and use require with your your-package-dir/index.js or exact location of module that you need. like this:

V8Object module = nvm.require(file);

Now you can call the function likes:

module.executeJSFunction("test");

To deliver entire dependencies you have to bundlize module directory your self.

What if you have to support cross-platform, refer https://www.npmjs.com/package/node-pre-gyp also.