【问题标题】:core-js is not polyfilling javascript codecore-js 不是 polyfill javascript 代码
【发布时间】:2022-08-12 14:46:13
【问题描述】:

我知道babel 可以在幕后使用 core-js 进行 polyfills。尽管如此,我仍然试图通过在没有 babel 的情况下使用 core-js(但将 js 与 webpack 捆绑)来了解 core-js 是如何工作的。

我像 $ npm i --save core-js 这样安装了 core-js 并将其添加到我的 index.js 文件之上(作为 official core-js documentation 中的用法之一):

import \'core-js\';

new Promise(function(resolve, reject) {
  let x = Math.random() * 500;
  let y = Math.random() * 500;
  setTimeout(() => resolve(\'Resolved\'), x);
  setTimeout(() => reject(new Error(\'Forced error\')), y);
}).then(function(result) {
  console.log(result);
}).catch(function(error) {
  console.log(error);
});

Promise.resolve(32).then(x => console.log(x));

console.log(Array.from(new Set([1, 2, 3, 2, 1])));

为了清楚地看到它生成的代码,我的 webpack.config.js 是这样的:

module.exports = {
  mode: \'development\',
  devtool: \'inline-source-map\'
};

在使用 $ npm run build(这是我运行 webpack 的脚本)构建它之后,我打开生成的 main.js,我注意到 PromisesArray.from()Set 仍然存在于最终代码中,还有很多代码来自核心 js。我期待代码以其他方式重写,所以我查看了代码并注意到在某些时候用这个var Promise = global.Promise; 分配了一些东西给变量 Promise,所以,这是否意味着这样,即使如果它在最终代码中显示为 Promises,它实际上会加载 core-js 代码来模拟 Promises?问题是,我在 IE 11 中尝试过,如果使用 Syntax Error 失败。

为了谨慎起见,我在 package.json 中添加了\"browsersList\": \"> 0.1%,ie10\"(我也尝试了默认值)。奇怪的是,在 core-js 文档中有一个online compiler 的链接,在那里,有一个预填充的代码,如果你点击编译,它不会改变 Promises 和 Set 和 Array.from () 任何一个。 PS.:在线编译器正在将箭头函数转换为常规函数,因此它必须在后台运行 babel。

然后,以防万一,我尝试只导入像 import \'core-js/features/promise\'; 这样的所需功能,但它没有改变任何东西(似乎就像在最终代码中出现 Promise 的第一种情况一样)。

我终于在 core-js 文档中尝试了第三种用法。通过将以下内容添加到我的 index.js 的顶部,我仅从 core-js 导入了功能承诺:import Promise from \'core-js/features/promise\';。我很清楚,现在 Promise 关键字实际上正在重新分配。构建后的最终代码如下(关于promise的部分):

new (core_js_features_promise__WEBPACK_IMPORTED_MODULE_0___default())(function(resolve, reject) {
  let x = Math.random() * 500;
  let y = Math.random() * 500;
  setTimeout(() => resolve(\'Resolved\'), x);
  setTimeout(() => reject(new Error(\'Forced error\')), y);
}).then(function(result) {
  console.log(result);
}).catch(function(error) {
  console.log(error);
});

core_js_features_promise__WEBPACK_IMPORTED_MODULE_0___default().resolve(32).then(x => console.log(x));

现在,正如预期的那样,代码确实已更改并且仍然有效(在节点、Chrome 或 Firefox 上,但在 IE 中不可用)。

我的问题是:

  • 当我使用import \'core-js\'; 全局导入core-js 并且promise 代码保持不变时,这是否意味着polyfill 仍然发生了?为什么它不能在 IE 上开始工作?我在这里错过了什么吗?

    标签: javascript webpack promise polyfills core-js


    【解决方案1】:

    我遇到了类似的问题,我相信这是因为 Webpack 的 Tree Shaking 功能,它将从最终包中删除未使用的代码。

    但我不确定,如果你有更多的细节或发现,请教我任何东西~

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多