Calling Dart from Javascript ... is it a bug?

Viewed 162

When compiling the following beautiful piece of code ...

@JS()
library nodejs;

import 'package:js/js.dart';

@JS()
class Exports {
  external set functionName(Function function);
}

@JS()
external Exports get exports;

void _someDartFunction(dynamic s) {
  print('Hello from Dirt!');
}

void main(List<String> arguments) {
  exports.functionName = allowInterop(_someDartFunction);
}

... from dart to js using the dart2js command like this:

dart2js -o node_modules/nodejs/index.js  bin/main.dart 

The nodule is called 'nodejs' (the name is not a problem in this context!). The module is initialised before by npm with an appropriate package.json.

Then I start nodejs and require the module

$ nodejs
> var n = require("nodejs")
ReferenceError: self is not defined
    at Object.main (/home/buergerling/Schreibtisch/dart/nodejs1/node_modules/njs/index.js:2544:28)
    at /home/buergerling/Schreibtisch/dart/nodejs1/node_modules/njs/index.js:3569:9
    at init.currentScript (/home/buergerling/Schreibtisch/dart/nodejs1/node_modules/njs/index.js:3549:7)
    at dartProgram (/home/buergerling/Schreibtisch/dart/nodejs1/node_modules/njs/index.js:3564:5)

getting an error. This problem can be solve be cancelling self from the compiled index.js file.

The problem can be spotted here:

...
  main: function($arguments) {
      var t1 = type$.Function;
      J.set$functionName$x(self.exports, P.allowInterop(D.main___someDartFunction$closure(), t1));
      J.set$functionName$x(self.module.exports, P.allowInterop(D.main___someDartFunction$closure(), t1));
      self.functionName = P.allowInterop(D.main___someDartFunction$closure(), t1);
      P.print("Hello from Dirt!");
    },
    Exports: function Exports() {
    }
...

Changing self.exports into exports solves the problem and the module can be loaded and used as expected.

Is there a more elegant solution than editing the compiled file by hand?

0 Answers
Related