webpack`this`没有指向窗口(Chart.js中断)

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

本文关键字:Chart js 中断 窗口 this webpack      更新时间:2023-09-26

我刚刚开始玩Webpack,并将一个较旧的应用程序从一组繁重的任务迁移到使用Webpack。到目前为止,它看起来很好,但我不知道如何让chart.js在这种情况下工作。

Chart.js正在尝试注册一个全局变量Chart,如下所示:

(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;

这实际上会中断,因为在webpack中运行时,thisundefined,而不是窗口或全局。

它引起的错误在行

root.Chart = Chart;

并说:

Uncaught TypeError: Cannot read property 'Chart' of undefined

有没有可能,我可以让Chart.js在不修补其源代码的情况下运行?事实上,它到处都在使用this技巧,我希望将来能够更新chart.js。

尝试使用导入加载程序来调整依赖上下文,如下所示:

安装带有npm install imports-loader 的装载机

并将其添加到webpack配置中的加载程序中:

{
    test: require.resolve('chart.js'),
    use: 'imports-loader?this=>window'
}