Webpack 4 / Babel 2功能在IE11中不起作用

时间:2018-07-07 14:45:03

标签: webpack babeljs

我是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()函数内部,并且是巨大的字符串。

1 个答案:

答案 0 :(得分:0)

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

float

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

对我来说,解决方案是编写两个新功能:

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

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

那为我解决了这个问题。

相关问题