【问题标题】:Webpack 4 / Babel 2 functions not working in IE11Webpack 4 / Babel 2 功能在 IE11 中不起作用
【发布时间】:2018-12-15 21:07:22
【问题描述】:

我是 Webpack / Babel 的新手。

我希望我能就此提出一个合理的问题,如果问题有点离题或者我无法提供所有必要的细节,请原谅我。

我只是在玩弄 webpack 和 babel,以便熟悉这两者。

我的目标是让一些 es6 js 在 IE 11 中工作。

堆栈如下所示:

"webpack": "^4.14.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
"babel-core": "^6.26.3",
"babel-cli": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",

js文件的Webpack配置规则:

{
  test: /\.js$/,
  exclude: /node_modules/,
  use: {loader: 'babel-loader'}
}

Babelrc:

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": [
            "ie >= 11"
          ]
        },
        "debug": true
      }
    ]
  ]
}

进入js文件:

require('babel-polyfill');
require('./index.html');
require('./scss/my.scss');
require('./js/my.js');

一切正常,我没有编译错误,编译后的资产按预期工作,并且在 Chrome 和 Firefox 中 100%,但在 IE11 中几乎一切正常。

现在在 my.js 文件中,我有以下函数用于着色和获取计算的样式属性值:

function shadeRGBColor(color, percent) {
    let f = color.split(',');
    let t = percent < 0 ? 0: 255;
    let p = percent < 0 ? percent*-1 : percent;
    let R = parseInt(f[0].slice(4));
    let G = parseInt(f[1]);
    let B = parseInt(f[2]);

    return "rgb("+(Math.round((t-R)*p)+R)+","+(Math.round((t-G)*p)+G)+","+(Math.round((t-B)*p)+B)+")";
}

function getStyle(el, styleProp) {
    if (el.currentStyle) return el.currentStyle[styleProp];

    return document.defaultView.getComputedStyle(el,null)[styleProp];
}

函数的示例用法如下所示:

const container = document.querySelector('.container');
const containerBackgroundColor = getStyle(container, 'backgroundColor');
const box = document.querySelector('.box');
box.style.backgroundColor = shadeRGBColor(containerBackgroundColor, 0.2);

我不知道它到底是什么,但是这段代码在编译/转译后在 IE11 中不起作用。

我还发现有趣的是,我编译的 js 有一些标准的 webpack 代码,但我所有的 js 代码都只是在一个 eval() 函数中作为一个巨大的字符串。

【问题讨论】:

    标签: webpack babeljs


    【解决方案1】:

    事实证明问题出在我的函数 getStyle() 上。

    function getStyle(el, styleProp) {
        if (el.currentStyle) return el.currentStyle[styleProp];
    
        return document.defaultView.getComputedStyle(el,null)[styleProp];
    }
    

    该函数在 Chrome/Firefox 中返回 rgb 颜色,但在 IE 中返回十六进制颜色。 因此,当颜色到达 IE 中的 shadeRGBColor() 时,它是十六进制颜色,所以问题从 shadeRGBColor() 名称本身就很明显了。

    我的解决方案是编写两个新函数:

    function isRGBColor(color) {
        return color.includes('rgb');
    }
    
    function convertHexToRGB(hexColor) {
        let hex = hexColor.replace('#','');
    
        let r = parseInt(hex.substring(0,2), 16);
        let g = parseInt(hex.substring(2,4), 16);
        let b = parseInt(hex.substring(4,6), 16);
    
        return 'rgb('+r+','+g+','+b+')';
    }
    

    这解决了我的问题。

    【讨论】:

      猜你喜欢
      • 2019-06-09
      • 2016-05-10
      • 2018-01-30
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      相关资源
      最近更新 更多