3

I've just started playing around with Webpack and migrating one older application from a set of grunt tasks to using webpack. It's looking very fine so far, however I can't figure out how to get chart.js working in that context.

Chart.js is trying to register a global variable Chart like this:

(function(){

"use strict";

//Declare root variable - window in the browser, global on the server
var root = this,
    previous = root.Chart;

//Occupy the global variable of Chart, and create a simple base class
var Chart = function(context){
    // some stuff
}

root.Chart = Chart;

This does actually break, because when run in webpack, this is undefined, rather than window or global.

The error it raises is in the line

root.Chart = Chart;

and says:

Uncaught TypeError: Cannot read property 'Chart' of undefined

Is there any chance, I can get Chart.js to run without patching it's source code? Actually it uses the this trick all over the place, and I want to be able to update chart.js in the future.

Matthias
  • 2,622
  • 1
  • 18
  • 29
  • We cannot see how this function is being invoked, but it's very bizarre that it would start with `"use strict";` and then assume that `this` is `window` on the *very next line*. One of very very well documented effects of using [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) is that `this` no longer defaults to `window`. Is the function by chance being invoked using `}).call(window)` at the end? – user229044 Mar 24 '16 at 19:58
  • I assume this is because the bundler wraps every module in something like this. Are you using the Babel loader? – Mike Cluck Mar 24 '16 at 20:01
  • It's vanilla chart.js - as to be found here: https://github.com/nnnick/Chart.js/blob/d2b73bdc5b5fd9b714dcab4c542eec750babd8bc/Chart.js It errors as the JS interpreter runs through webpacks generated JS file – Matthias Mar 24 '16 at 20:01
  • yes, using babel loader – Matthias Mar 24 '16 at 20:01
  • Then you'll need to make sure the `strict-mode` plugin isn't being used in Babel. [See this question here.](http://stackoverflow.com/questions/33821312/how-to-remove-global-use-strict-added-by-babel) – Mike Cluck Mar 24 '16 at 20:04
  • Thanks for the hint. Now trying to figure out how to tell the babel loader to use a blacklist. The hard part in webpack is definitely the documentation... – Matthias Mar 24 '16 at 20:10
  • It's a bug in the library - just fix it by changing the very last line from `.call(this)` to `.call(window || global)` and send them a pull request. – georg Mar 24 '16 at 20:21

1 Answers1

0

try to use imports-loader to adjust dependency context like this:

Install the loader with npm install imports-loader

and add it to loaders in your webpack configuration:

{
    test: require.resolve('chart.js'),
    use: 'imports-loader?this=>window'
}
Roman86
  • 1,990
  • 23
  • 22