trading-peter / chart-elements

Chart.js as Polymer Elements
https://robdodson.github.io/chart-elements
267 stars 70 forks source link

How to use with polymer-webpack-loader #73

Closed frasun closed 6 years ago

frasun commented 6 years ago

I am having problems integrating chart components with app that usespolymer-webpack-loader. I am getting the error:

ReferenceError: ChartBehaviors is not defined

seems like ChartBehaviors is not available as window object. It works if I change the files code manually, but that is not an option. Adding these lines to chart-property-behavior.html, context-behavior.html and resize-behavior.html fix the problem:

var ChartBehaviors = ChartBehaviors || {};
...
window.ChartBehaviors = ChartBehaviors

Any help in getting this to work e.g. from the webpack configuration level would be very appreciated :)

robdodson commented 6 years ago

Sorry for not replying sooner, I'm about to head out on vacation. My webpack knowledge isn't super hot, but if you look at the polymer webpack loader repo there is a thread on polymer-redux which maybe explains how to address a similar problem.

frasun commented 6 years ago

I left this for some time and finally managed to get it to work. Of course it was webpack related issue so thanks for pointing me to the right direction on this :)

I will post my solution if anyone has a similar case. In order to use chart-elements with webpack I had to first use exports-loader to expose the ChartBehaviors

// webpack.config.js 
{
  test: [
    path.resolve(__dirname, 'bower_components/chart-elements/chart-property-behavior.html'),
    path.resolve(__dirname, 'bower_components/chart-elements/context-behavior.html'),
    path.resolve(__dirname, 'bower_components/chart-elements/resize-behavior.html')
  ],
  use: 'exports-loader?ChartBehaviors'
},

then I created sepate module for providing ChartBehaviors object:

// ChartBehaviors.js
import resizeBehavior from 'chart-elements/resize-behavior.html'
import contextBehavior from 'chart-elements/context-behavior.html'
import chartPropertyBehavior from 'chart-elements/chart-property-behavior.html'

export default {
  ...resizeBehavior,
  ...contextBehavior,
  ...chartPropertyBehavior
}

finally I used ProvidePlugin to point to the file that will resolve required object:

// webpack.config.js
new webpack.ProvidePlugin({
    'ChartBehaviors': [path.resolve(__dirname, 'polymer_components/utils/ChartBehaviors.js'), 'default']
  })
robdodson commented 6 years ago

cool thank you for documenting all of this work!