Reputation: 7922
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:
flutter
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
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:
print() -> console.log(...)
, so the example uses the undocumented print(...)
(aliased from Dart I guess?)Upvotes: 2