index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
<script src="https://google.github.io/traceur-compiler/src/bootstrap.js"></script>
<script>
traceur.options.experimental = true;
</script>
<link rel="import" href="x-item.html">
</head>
<body>
<x-item></x-item>
</body>
</html>
和我的网络组件: x-item.html
<template id="itemtemplate">
<span>test</span>
</template>
<script type="module">
class Item extends HTMLElement {
constructor() {
let owner = document.currentScript.ownerDocument;
let template = owner.querySelector("#itemtemplate");
let clone = template.content.cloneNode(true);
let root = this.createShadowRoot();
root.appendChild(clone);
}
}
Item.prototype.createdCallback = Item.prototype.constructor;
Item = document.registerElement('x-item', Item);
</script>
我没有收到任何错误,也没有收到我期望显示的内容,您知道这是否真的有效吗?
这是用 ECMA6 语法扩展 HTMLElement 的方式吗?
E:将它完全放在一个页面中解决了问题,至少现在我知道这是创建自定义组件的正确方法,但问题是将它放在一个单独的文件中,我认为它有与 Traceur 如何处理有关 <link rel="import" href="x-item.html">
我尝试将 type 属性添加到导入中,但没有成功。
最佳答案
Traceur 的内联处理器似乎不支持查找 <script>
里面的标签<link import>
。 Traceur 的所有代码似乎都访问 document
直接,这会导致 Traceur 只查看 index.html 而看不到任何 <scripts>
在 x-item.html 内。这是一个适用于 Chrome 的解决方法。将 x-item.html 更改为:
<template id="itemtemplate">
<span>test</span>
</template>
<script type="module">
(function() {
let owner = document.currentScript.ownerDocument;
class Item extends HTMLElement {
constructor() {
// At the point where the constructor is executed, the code
// is not inside a <script> tag, which results in currentScript
// being undefined. Define owner above at compile time.
//let owner = document.currentScript.ownerDocument;
let template = owner.querySelector("#itemtemplate");
let clone = template.content.cloneNode(true);
let root = this.createShadowRoot();
root.appendChild(clone);
}
}
Item.prototype.createdCallback = Item.prototype.constructor;
Item = document.registerElement('x-item', Item);
})();
</script>
<script>
// Boilerplate to get traceur to compile the ECMA6 scripts in this include.
// May be a better way to do this. Code based on:
// new traceur.WebPageTranscoder().selectAndProcessScripts
// We can't use that method as it accesses 'document' which gives the parent
// document, not this include document.
(function processInclude() {
var doc = document.currentScript.ownerDocument,
transcoder = new traceur.WebPageTranscoder(doc.URL),
selector = 'script[type="module"],script[type="text/traceur"]',
scripts = doc.querySelectorAll(selector);
if (scripts.length) {
transcoder.addFilesFromScriptElements(scripts, function() {
console.log("done processing");
});
}
})();
</script>
另一种可能的解决方案是将 ECMA6 预编译为 ECMA5 并仅包含 ECMA5。这将避免traceur找不到<script>
的问题导入中的标签,并且将消除对样板的需要。
关于javascript - 使用 ECMA6 的 Web 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27576979/