webpack `this` not pointing to window (Chart.js breaks)

Viewed 776

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.

1 Answers

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'
}
Related