Modules in Polymer

送分小仙女□ 提交于 2019-12-12 13:16:32

问题


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.

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

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

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.


回答1:


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. 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>
    
  2. Use some kind of plugin to import HTML from ES6 code. This is, for example, possible with this plugin for SystemJS

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

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.

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.



来源:https://stackoverflow.com/questions/39690653/modules-in-polymer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!