I need to use node-java node_module in my typescript project.
However,
var java = require("java");
does not work in typescript way, and also
import java = module("java");
does not work as it is.
I know we may need a definition file etc. and there's a project like https://github.com/borisyankov/DefinitelyTyped
Having said that, I think it's way too complicated to do by myself.
Is there any easier workaround? Thanks.
The best way is use a definition file to node-java API, however, using your first code snippet:
var java = require("java");
you can use a reference to this node typing as following:
/// <reference path="node/node.d.ts" />
var java = require("java");
java.classpath.push("commons-lang3-3.1.jar");
java.classpath.push("commons-io.jar");
var list = java.newInstanceSync("java.util.ArrayList");
java.newInstance("java.util.ArrayList", function(err, list) {
list.addSync("item1");
list.addSync("item2");
});
var ArrayList = java.import('java.util.ArrayList');
var list2 = new ArrayList();
list.addSync('item1');
To use the second snippet:
import java = module("java");
you will need a definition file. To a kick start you can create a node-java.d.ts file with the following code:
module "java" {
export var classpath: { push(jar: string); };
export function newInstanceSync(type: string);
export function newInstance(type: string, callback: (err, list) => any);
export function import(type: string);
export function newArray(...item: any[]);
export function callStaticMethodSync(...args: any[]);
}
And use this file as following:
/// <reference path="node-java.d.ts" />
import java = module("java");
java.classpath.push("commons-lang3-3.1.jar");
java.classpath.push("commons-io.jar");
var list = java.newInstanceSync("java.util.ArrayList");
java.newInstance("java.util.ArrayList", function(err, list) {
list.addSync("item1");
list.addSync("item2");
});
var ArrayList = java.import('java.util.ArrayList');
var list2 = new ArrayList();
list.addSync('item1');
Having time, I'll send a node-java definition to DefinitelyTyped repository.
When you say that this doesn't work:
var java = require("java");
I'm assuming you get an error directly calling require because it doesn't have type information.
One way to solve this is to add type information for require:
declare var require: (module: string) => any;
var java = require('java');
This is a simplistic example - java won't be typed as the return value of require in my example is any - but if you had type information you could cast it:
declare var require: (module: string) => any;
var java = <JavaDefinition> require('java');