3

我想在没有 Dart VM 的浏览器上将 Dart API 导出到 JavaScript。例如,给定一个 A 类:

class A {
  String name;

  A();

  A.withName(this.name);
}

我想使用导出的 API 创建一个 JavaScript 对象:

var a = new A();

对我上一个问题的回答将我指向 js-interop。

但是,在完成README 示例时,我无法获得预期的结果。看来我的 Dart 库没有被导出到 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

示例/main.dart

图书馆主:

import 'package:js/js.dart';

main() {
  initializeJavaScript();
}

库/a.dart

library a;

import 'package:js/js.dart';

@Export()
class A {
  String name;

  A();

  A.withName(this.name);
}

索引.html

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

(不清楚最后一个脚本标签的 src 属性应该指向哪里。我也尝试过使用 /example/main.dart ,这不会改变我的结果。)

我希望能够在编译(Tool -> Pub Build)并加载 index.html 后打开控制台,然后执行以下操作:

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

但是,我得到了这个:“无法读取未定义的属性'A'”。换句话说,dart.a是未定义的。

在 index.html 中包含原始 Dart 脚本表明 js-interop 适用于带有 Dart VM 的浏览器。我尝试在 Dartium 上运行 index.html,结果相同。

我错过了什么?

4

2 回答 2

2

Yes, it does work on a JavaScript only browser. It turns out the documentation doesn't give all of the steps. Here's what worked for me, starting with a new project.

Create a new package project called 'jsout' using (File-> New Project/package). Delete these files:

  • test/all_test.dart
  • example/jsout.dart

Edit these files:

pubspec.yaml

name: jsout
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

lib/main.dart

part of main;

@Export()
class A {
  String name;

  A();

  A.withName(this.name);

  talk() {
    print(name);
  }
}

Create folder web, and add these files:

web/main.dart

library main;

import 'package:js/js.dart';

part '../lib/jsout.dart';

main() {
  initializeJavaScript();
}

web/index.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <script src="main.dart_initialize.js"></script>
    <script src="main.dart.js"></script>
  </body>
</html>

After updating these files, load index.html, and open a console:

var a = new dart.main.A.withName('foo');

a.talk(); // returns 'foo'

This procedure worked as of revision 7afdb.

于 2014-12-06T00:42:31.043 回答
2

script 标签的src属性仍然必须指向一个包含main()方法的带有 Dart 脚本的文件。当应用程序使用pub buildDart 构建为 JavaScript 时,它会被编译为 JavaScript,并且可以在没有 Dart VM 的浏览器中运行。

于 2014-12-05T21:39:00.790 回答