Babel 7:Function.prototype.toString:“此”不是Function对象

Kat*_*ine 3 javascript babel web-component gulp gulp-babel

我想创建应该在ie11上运行的Web组件。我正在用gulp(和gulp-babel,其中包括babel 7)编译js。

到目前为止,当我使用Babel进行编译时,它可以在Chrome中运行,但是会在ie11:中发送错误Function.prototype.toString: 'this' is not a Function object

在gulpfile.js中,我有这个:

.pipe(babel({
    "presets": [
        ["@babel/preset-env", {
            "targets": {
                "browsers": [
                    "Chrome >= 52",
                    "FireFox >= 44",
                    "Safari >= 7",
                    "Explorer 11",
                    "last 4 Edge versions"
                ]
            }
        }]
    ]
}))
Run Code Online (Sandbox Code Playgroud)

在js中,我有类似这样的内容(我在网上找到了用于测试的示例代码):

class MyCustomTag extends HTMLElement {
    connectedCallback() {
        this.innerHTML = '<h2>My custom element</h2><button>click me</button>';
        this.style.backgroundColor = 'blue';
        this.style.padding = '20 px';
        this.style.display = 'inline-block';
        this.style.color = 'white';
    }
}

try {
    customElements.define('my-custom-tag', MyCustomTag)
} catch (err) {
    const h3 = document.createElement('h3')
    h3.innerHTML = "This site uses webcomponents which don't work in all browsers! Try this site in a browser that supports them!"
    document.body.appendChild(h3)
}
Run Code Online (Sandbox Code Playgroud)

当然,我添加<my-custom-tag></my-custom-tag>了HTML。

当代码中存在“ extends HTMLElement”时,该错误将引发Babel生成的错误(如果我记得很好,Babel会使用Function.prototype.Tostring生成类似“ _.isNative”的错误-很抱歉,我当前在另一台计算机上)我确定我缺少一些愚蠢的东西,但是找不到该错误的答案。我尝试添加@ babel / plugin-transform-classes,babel-plugin-transform-b​​uiltin-classes,但是没有任何效果,这使我发疯。

任何的想法?

Mar*_*ink 5

我只是在完全相同的问题上浪费了时间!我首先怀疑Webpack做一些奇怪的事情,然后我认为这是Babel等的问题。

最后我发现,您需要加载webcomponents.js polyfill才能针对IE11进行修复!方法如下:

npm install @webcomponents/webcomponentsjs
Run Code Online (Sandbox Code Playgroud)

然后将polyfill加载到HTML文件的头部:

<!-- load webcomponents bundle, which includes all the necessary polyfills -->
<script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>
Run Code Online (Sandbox Code Playgroud)

现在,甚至IE都应该可以很好地与您的Web组件配合使用。