聚合物模块 [英] Modules in Polymer

查看:81
本文介绍了聚合物模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的React项目中,我已经使用ES6模块一段时间了.在我的react组件中,我将使用import:

In my react projects I have been using ES6 modules for some time. In my react component I would use import:

import {f1,f2} from "./myLib";

在聚合物组件中,我使用脚本标签:

In my polymer component I use a script tag:

<script src="./myLib.js"></script>

如果我没记错的话,它们正在做两种完全不同的事情.脚本标记正在污染整个应用程序的全局名称空间.导入不是.

If I'm not mistaken, these are doing two totally different things. The script tag is polluting my global namespace for the whole app. The import isn't.

问题#1:我对这一点的理解正确吗?

Question #1: Am I correct in my understanding of this?

问题2:有没有办法得到类似的聚合物?

Question #2: Is there a way to get something similar in polymer?

我有数十种不同的聚合物成分.一些导入冲突的库.然后,如果我的页面使用了多个组件,那么我将获得关于哪个版本的JS脚本的胡言乱语.

I have dozens of different polymer components. Some import conflicting libraries. Then, if I have a page that uses multiple components it seems like a crap shoot as to which version of the JS script I will get.

推荐答案

当然可以将ES6模块与Polymer一起使用.您要做的第一件事是拆分模板和脚本.然后,您可以同时使用两种方式

It is certainly possible to use ES6 modules with Polymer. First thing you will have to do is split the template and script. You can then go both ways

  1. 将包含转译的ES6代码的脚本标签添加到元素的html:

  1. Add a script tag containing transpiled ES6 code to the element's html:

<dom-module id="my-elem"></dom-module>
<script src="my-elem.js"></script>

  • 使用某种插件从ES6代码导入HTML.例如,可以使用此针对SystemJS的插件

    import './my-elem.html!';
    
    class MyElem extends HTMLElement {}
    
    document.registerElement('my-elem', MyElem);
    

  • 然后,最困难的部分就是转嫁.我不确定其他模块加载程序,但是使用JSPM + SystemJS可以很容易地将其捆绑为通用模块.这样,您的元素既可以被<link rel="import" href="bower_components/my-elem/my-elem.html">使用,又可以从其他ES6代码导入.在前一种情况下,任何未捆绑的依赖项都必须存在于全局范围内.但是,您可以将任何此类依赖项放在主html文件中.就像发布了许多其他元素一样.

    Then the difficult part is then transpiling. I'm not sure about other module loaders, but with JSPM+SystemJS it is easy to bundle as an Universal module. This way your element will be usable both by <link rel="import" href="bower_components/my-elem/my-elem.html"> and for importing from other ES6 code. In the former case any dependencies not bundled will have to live in the global scope. You could, however, place any such dependencies in your main html file. Just like many other elements are published.

    如果您愿意尝试JSPM + SystemJS,请查看我的博客上的博客帖子.我使用的是TypeScript,但对于ES6,一般的解决方案应该大致相同.

    If you're willing to give JSPM+SystemJS a try, please have a look at a blog post on my blog. I'm using TypeScript but for ES6 the general solution should be roughly the same.

    这篇关于聚合物模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆