Edmond Tamas Edmond Tamas - 21 days ago 6
Node.js Question

Is it possible to import modules into a Polymer component?

I would like to keep my polymer components nicely encapsulated but right now if I try to import any external modules into the components I get an undefined error for 'import'.

I use Webpack to bundle up my app but this packs up my javascript files only.

Is there a way to do keep my Polymer component encapsulated into a single html file or I must separate the js part when it comes to imports?

Example:

<link rel="import" href="../bower_components/polymer/polymer.html">

<dom-module id="my-new-view">
<template>
<style>
</style>

<h1>New view</h1>
</template>

<script>

import { myConstant } from '../module.js'; //<---- this throws error for the import'

Polymer({
is: 'my-new-view'
});
</script>
</dom-module>

Answer

Only Webpack

For it to work like that, you'd have to export module.js as a library so it can be used outside of Webpack. Once it's part of a library and included in the global scope you can then access it like

var myConstant = Module.myConstant;

Polymer({
  is: 'my-new-view'
});

It's likely much easier to just have your JS code in a separate file.

See http://stackoverflow.com/a/34361312/4722305.

Crisper

One other option might be to run https://github.com/PolymerLabs/crisper over your code before calling into webpack. Crisper will remove the <script> tags from your code and convert them into JS files that will be compatible with Webpack.