对于这样的代码:
const top = document.createElement("div");
top.innerText = "This is the top";
top.style = red;
export { top };
Webpack 创建以下内容:
...
"use strict";
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, "top", function() { return top; });
...
const top = document.createElement("div");
top.innerText = "This is the top";
top.style = red;
既然在 getter function() { return top; 内部,这怎么能起作用呢? }
,脚本执行时top
尚未定义?
Webpack 在顶部而不是底部创建导出是否有特殊原因?
谢谢。
最佳答案
整个js文件作为一个整体进行评估。 webpack 生成的代码部分正在创建一个稍后调用的回调函数。特别是当用户代码 require
或 import
相关模块时。
稍后在脚本中,将评估模块的内容并定义变量 top
,这保证在 webpack 执行 function() { return top; 之前发生。 }
这只是在 JavaScript 中使用变量之前声明或定义变量的约定,而不是必需的。可以通过引用父作用域中尚 undefined variable 来安全地创建函数作用域,只要它们在函数执行时定义即可。
关于javascript - webpack 包中的导出顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51978704/