如何使用ECMAScript 6模块导入PlotlyJS

时间:2019-03-03 05:06:44

标签: javascript ecmascript-6 module plotly.js

我正在尝试使用这样的ES6模块实现PlotlyJS(last version):

index.html

<script src="main.js" type="module"></script>

main.js

import * as Plotly from './plotly.js';

但是我有此错误“ Uncaught TypeError:无法读取plotly.js中未定义的属性'document'”

plotly.js:21576 Uncaught TypeError: Cannot read property 'document' of undefined
at plotly.js:21576
at Object.151 (plotly.js:31122)
at o (plotly.js:7)
at plotly.js:7
at Object.699.../constants/numerical (plotly.js:102912)
at o (plotly.js:7)
at plotly.js:7
at Object.1.../src/lib (plotly.js:10)
at o (plotly.js:7)
at plotly.js:7

我认为问题出在图书馆。有想法吗?

Line of error code in plotly.js

2 个答案:

答案 0 :(得分:0)

这是错误[原生ES6模块与捆绑包] [https://github.com/plotly/plotly.js/issues/3518]

您必须等待plotly.js 2.0版或根据打开器进行修复

  

我通过从}()更改了27724行来修复了它; } .apply(self);但这只是一个hack:)

当然,确切的行是移动的目标,具体取决于您使用的发行版。

答案 1 :(得分:0)

如果有人想在 node_module 中实施更改并使用更激进的方法,请利用 patch-package 实用程序。

在 package.json 脚本中,可以使用以下命令修补 node_modules

"postinstall": "./node_modules/.bin/patch-package"

plotly 1.58.4 的补丁

diff --git a/node_modules/plotly.js/dist/plotly-with-meta.js b/node_modules/plotly.js/dist/plotly-with-meta.js
index 1aaac5a..cb3ecfe 100644
--- a/node_modules/plotly.js/dist/plotly-with-meta.js
+++ b/node_modules/plotly.js/dist/plotly-with-meta.js
@@ -35864,7 +35864,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
     return request.responseXML;
   });
   if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3;
-}();
+}.apply(self);
 },{}],170:[function(_dereq_,module,exports){
 module.exports = function () {
     for (var i = 0; i < arguments.length; i++) {
diff --git a/node_modules/plotly.js/dist/plotly.js b/node_modules/plotly.js/dist/plotly.js
index 365230c..6268511 100644
--- a/node_modules/plotly.js/dist/plotly.js
+++ b/node_modules/plotly.js/dist/plotly.js
@@ -35864,7 +35864,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
     return request.responseXML;
   });
   if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3;
-}();
+}.apply(self);
 },{}],170:[function(_dereq_,module,exports){
 module.exports = function () {
     for (var i = 0; i < arguments.length; i++) {

d3 3.5.17 补丁

diff --git a/node_modules/d3/d3.js b/node_modules/d3/d3.js
index aded45c..d5b3cad 100644
--- a/node_modules/d3/d3.js
+++ b/node_modules/d3/d3.js
@@ -9551,4 +9551,4 @@
     return request.responseXML;
   });
   if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3;
-}();
\ No newline at end of file
+}.apply(self);