ES6 - 自定义元素不与webpack一起使用

时间:2017-07-17 01:18:07

标签: webpack ecmascript-6 custom-element

我正在尝试使用带有webpack的ES6创建自定义元素

https://codepen.io/nagasai/pen/MoRrxO

下面的代码可以在没有webpack的情况下使用

HTML:

<my-element><my-element>

JS:

class MyElement extends HTMLElement {
   constructor() { super() } 
    connectedCallback() {
       this.innerHTML =`<input type="text" onclick="display()">`;
    }
  }

  customElements.define('my-element', MyElement);

function display(){
  alert("hiii");
}

当我使用webpack尝试上面的代码时,它失败并出现以下错误

Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

请找到以下文件夹结构和webpack.config.js文件

enter image description here

webpack.config.js文件:

module.exports={
  entry:'./assets/js/scripts.js',
  output:{
    filename:'./lib/js/lib.js'
  },
  module:{
    loaders:[
      {
        test: /\.js$/,
        exclude:/node_modules/,
        loader:'babel-loader',
        query:{
          presets:['es2015']
        }
      }
    ]
  }
}

的index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

<my-element></my-element>
  <script src="./lib/js/lib.js"></script>
  </body>
</html>

package.json:

{
  "name": "es6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-preset-es2015": "^6.24.1"
  }
}

只有最接近我的问题的答案是extending HTMLElement: Constructor fails when webpack was used,但它是打字稿,但我的代码中提供了ES2015的转换

0 个答案:

没有答案