tresf
tresf

Reputation: 7922

How can I run JavaScript in Dart?

Dart officially provides JavaScript language support through the Dart web platform but for projects not using the web platform, there's unofficial support through a project called JSParser.

Due to my unfamiliarity with the language combined with sparse documentation, I'm not sure how to use this JSParser library. The example looks like this:

import 'package:parsejs/parsejs.dart';

void main() {
    new File('test.js').readAsString().then((String code) {
        Program ast = parsejs(code, filename: 'test.js')
        // Use the AST for something
    })
}

After installing the ParseJS library, the above code compiles just fine. But how do I interact with "the AST"? The IDE's code hinting doesn't seem to help either.

Looking back on the history of this project, it seems to have exchanged hands multiple times however all seem to be missing an example of what is done with the ast object afterward.

Steps I've done:

Are these libraries too old or am I just using them wrong? How would I know? I'm on Dart 2.11

Upvotes: 2

Views: 1576

Answers (1)

tresf
tresf

Reputation: 7922

After combining a few examples, notably this GitHub project and this unit test, I can get the interpreter to work.

dependencies:
  dartjsengine: ^1.0.1
  jsparser: ^2.0.1

Note, this uses JSEngine().visitProgram(...) combined with the parsejs() function from JSParser.

import 'package:dartjsengine/dartjsengine.dart';
import 'package:jsparser/jsparser.dart';

main() {
  JsObject myObj = JSEngine().visitProgram(parsejs('var a = "red"; var b = "blue"; print(a); b;', filename: 'ignore'));
  print('${myObj?.valueOf}');
}

Outputs:

red
blue

Some major caveats:

  • There's no alias from print() -> console.log(...), so the example uses the undocumented print(...) (aliased from Dart I guess?)
  • Several language features seem to be missing, importing an existing file as-is likely to fail.

Upvotes: 2

Related Questions