Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving methods during dart2js minification and tree-shaking

Tags:

dart

dart2js

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?

like image 296
spierce7 Avatar asked Oct 20 '22 16:10

spierce7


1 Answers

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>
like image 182
hkk Avatar answered Dec 05 '22 15:12

hkk