2

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:

  • Installed flutter
  • Installed and configured IntelliJ to use the flutter runtime I've installed
  • Installed the beta Desktop support for flutter
  • Installed the library and try to run the example

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

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.