2

I am trying to create custom elements using ES6 with webpack

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

Below code works without 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");
}

When I try above code with webpack , it fails with below error

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

Please find the below folder structure and webpack.config.js file

enter image description here

webpack.config.js file :

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"
  }
}

Only answer closest to my issue is extending HTMLElement: Constructor fails when webpack was used but it is with typescript but transpiling for ES2015 is available in my code

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
  • Typescript is a compiler just like Babel. If Typescript can't do it without shims like that other question, neither can Babel. – loganfsmyth Jul 17 '17 at 01:24
  • I have used the below cdn for HTML Custom Elements Polyfill but no luck https://cdnjs.cloudflare.com/ajax/libs/custom-elements/1.0.0/custom-elements.min.js – Naga Sai A Jul 17 '17 at 01:44
  • remove the constructor() call or look at this other question https://stackoverflow.com/q/41414034/4600982 – Supersharp Jul 17 '17 at 17:33
  • same error - Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function. No luck :( – Naga Sai A Jul 17 '17 at 19:47

0 Answers0