首页 > 解决方案 > 如何阻止 babel 将“this”(用作 IIFE 参数)转换为“void 0”?

问题描述

我想将 ES6 转换为 ES5,因为我们被迫支持 IE11 并且在使用现代脚本时遇到了一些麻烦。我的捆绑包包含 Sweetalert2 并window获得了undefinedbabel。

输入

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.Sweetalert2 = factory());
}(this, (function () { 'use strict'; 
    // ...

babel 处理后:

(function (global, factory) {
  (typeof exports === "undefined" ? "undefined" : _typeof2(exports)) === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.Sweetalert2 = factory();
})(void 0, function () {
  'use strict';
// ....

我发现How to stop babel from transpiling 'this' to 'undefined'并且由于 preset-es2015 包被认为已弃用,我认为@babel/preset-env对我的 babel7 使用 up2date repalcement 是"esmodules": false但它不起作用。

.babelrc

{
  "ignore": ["gulpfile.js"],
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "esmodules": false
        }
      }
    ]
  ]
}

标签: javascriptecmascript-6babeljsecmascript-5

解决方案


推荐阅读