Dart. How to use @HtmlImport on the example of Pol

2019-01-20 02:09发布

问题:

I've read the doc explains @HtmlImprot implementation (https://github.com/dart-lang/polymer-dart/wiki/Dart-to-HTML-imports), but my English isn't good enough and I still have a little doubts about using it. Please, consider the example:

index.html

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="main.css"/>
</head>
<body>
<app-element></app-element>

<script type="application/dart" src="main.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>

main.dart

@HtmlImport('templates/ui-elements.html')
library main;

import 'dart:html';
import 'package:polymer/polymer.dart';

main() {
  initPolymer();
}

@whenPolymerReady
void onReady() {
  print('polymer is loaded');
}

templates/ui-elements.html

<link rel="import" href="../packages/polymer/polymer.html">
<polymer-element name="ui-button" noscript>
  <template>
    <h2>app-element# > ui-button# > h2</h2>
  </template>
</polymer-element>

<polymer-element name="app-element" noscript>
  <template>
    <h2>app-element# > h2</h2>
    <ui-button></ui-button>
  </template>
</polymer-element>

Questions:

  • Why I have to use library name; declaration?
  • Are there any difference between using @HtmlImport and <link rel="import" href=""/>?
  • Is it normal to store all polymer-element's HTML in one HTML file?
  • Is it normal to store all @CustomTag() declaration in the one dart file?

Thank you in advance.


At the first time I had the problem with cache. I don't know maybe it was @HtmlImport or browser itself, but whatever changes I made nothing had changed in templates/ui-elements.html's content.

回答1:

Why I have to use library name; declaration?

We had to stick it somewhere, and all files should have a library declaration anyways. It is also near your dart imports which is kind of nice.

Are there any difference between using @HtmlImport and ?

@HtmlImport just injects an <link rel="import"> into the page. It has advantages though such as supporting package: style imports and also allowing your dart dependencies to declare their own html dependencies, instead of you having to know about both.

Is it normal to store all polymer-element's HTML in one HTML file?

I would not recommend doing this. In general your life will be easier if each element has its own html file and dart file.

Is it normal to store all @CustomTag() declaration in the one dart file?

Same answer as above, I would stick each elements class in its own file.