I have a few files that I have written in dart that I want to compile to javascript and include in a few html files that are running in my Android application.
The files consist of a main method, then there is an api layer with 3 functions that other javascript code will call at run-time. It's very important that I include as little of dart's libraries as possible (so tree-shaking is a must), and when the tree-shaking / minification process happens, I need to ensure that the 3 api layer functions don't get renamed / optimized out because it thinks they aren't being called?
How do I tell dart2js to leave the signature of certain functions alone, and not to prune them out because it thinks they aren't being used?
You can use the dart:js
library's context
property, a JsObject
which allows you to expose variables and methods from dart to JavaScript, and will be preserved by dart2js. In your main method, simply include context['jsMethodName'] = dartMethodName
, and then call it in your JavaScript. Here's an example:
library.dart
import 'dart:js';
void main(){
print("main called!");
context['myMethod'] = myMethod;
}
void myMethod(){
print("My Method Called!");
}
index.html
<script src="library.dart.js"></script>
<script>
console.log(myMethod());
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With