Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting Dart APIs to JavaScript, without a Dart VM

I'd like to export a Dart API to JavaScript on browsers without a Dart VM. For example, given a class A:

class A {
  String name;

  A();

  A.withName(this.name);
}

I'd like to create a JavaScript object using the exported API with:

var a = new A();

An answer to my previous question pointed me to js-interop.

However, I'm not able to get the expected result when working through the README example. It appears that my Dart library isn't being exported into JavaScript.

pubspec.yaml:

name: interop
description: >
  A library useful for applications or for sharing on pub.dartlang.org.
version: 0.0.1
dev_dependencies:
  unittest: any
dependencies:
  js:
    git:
      url: git://github.com/dart-lang/js-interop.git
transformers:
  - js
  - js/initializer

example/main.dart

library main:

import 'package:js/js.dart';

main() {
  initializeJavaScript();
}

lib/a.dart

library a;

import 'package:js/js.dart';

@Export()
class A {
  String name;

  A();

  A.withName(this.name);
}

index.html

<html>
  <head>
    <script src="packages/js/interop.js"></script>
  </head>
  <body>
    <script type="application/dart" src="build/example/main.dart"></script>
  </body>
</html>

(It's not clear where the src attribute of that last script tag should point. I've tried using /example/main.dart as well, which doesn't change my result.)

I expected to be able to open a console after compiling (Tool -> Pub Build) and loading index.html, and then do this:

var a = new dart.a.A();

However, I get this instead: "Cannot read property 'A' of undefined". In other words, dart.a is undefined.

The inclusion of raw Dart script in index.html suggests that js-interop is intended for a browser with a Dart VM. I tried running index.html on Dartium with the same result.

What am I missing?

like image 919
Rich Apodaca Avatar asked Jan 18 '26 03:01

Rich Apodaca


1 Answers

The src attribute of the script tag still has to point to a file with a Dart script that contains a main() method. When the application is built to JavaScript using pub build Dart is compiled to JavaScript and can be run in browsers without a Dart VM.

like image 137
Günter Zöchbauer Avatar answered Jan 19 '26 15:01

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!