Coder Social home page Coder Social logo

babel-plugin-transform-custom-element-classes's Introduction

babel-plugin-transform-custom-element-classes

Compile Custom Element classes that extend HTMLElement for ES5 environments.

Problem

Custom Elements were designed for native ES6 classes that can extend host objects in ways prototypical inheritance can not. Using the Babel transform-es2015-classes transform will not work as is. You'll likely see a runtime error like "Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function." when attempting to extend HTMLElement in a Babel transpiled class.

Solution

A workaround is to use Reflect.construct to build a new HTMLElement instance expected by the constructor. This transform wraps any ES6 classes extending HTMLElement with an intermediary class that shims this behavior.

Compatibility

Chrome Firefox IE Opera Safari
Latest ✅ 10.1+ TP ✅
Chrome Firefox IE Opera Safari
Latest ✅ Latest ✅ 11 ✅ Latest ✅ 9.1+ ✅

Installation

$ npm install babel-plugin-transform-custom-element-classes

Usage

Via .babelrc

.babelrc

// include before transform-es2015-classes
{
  "plugins": [
    "transform-custom-element-classes",
    "transform-es2015-classes"
  ]
}

babel-plugin-transform-custom-element-classes's People

Contributors

josh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

babel-plugin-transform-custom-element-classes's Issues

Won't work with mixins

We often have mixins that are applied like so:

class MyElement extends Templating(HTMLElement) {
  ...
}

Which won't trigger the transform.

compiled ES6 element class constructor called twice in IE11 and Firefox 51

I'm trying to use your plugin to support customElements using ES2015 class in an ES5 environment ( such as IE).
My problem is that whenever I add my element object to the dom, his constructor is called a second time ( IE11 and Firefox51)

.babelrc

// include before transform-es2015-classes
{
  "plugins": [
    "transform-custom-element-classes",
    "transform-es2015-classes"
  ]
}

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <base href="/">
    <title>Test</title>
  </head>
  <body>
    <!-- shim for Reflect support  https://github.com/paulmillr/es6-shim-->
    <script type="text/javascript" src="lib/es6-shim/es6-shim.js"></script>
    <!-- customElements V1 polyfill https://github.com/webcomponents/custom-elements-->
    <script type="text/javascript" src="lib/webcomponents/custom-elements.js"></script>
    <script type="text/javascript" src="test.js"></script>
  </body>
</html>

test.js

var instances = [];
var count = 0;
function alreadyRegistered(instance){
	for(var i =0;i<instances.length;i++){
		if(instances[i] == instance)
			return true;
	}
	return false;
}

class fooElement extends HTMLElement{

	constructor(){
		super();
		
		if(alreadyRegistered(this) === true){
			console.log("constructor already called");
		}
		instances.push(this);
		this.innerHTML = "count:"+count+";";
		count++;
	}

}

customElements.define("foo-element",fooElement);
var bar = new fooElement();

document.body.appendChild(bar);

console output in IE11 and Firefox 51:

constructor already called

and innerHTML

count:1;

Am I doing something wrong ?

Possible to use with MediaSource?

When I extend MediaSource, I receive the error:

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

This seems to be a similar problem that your library addresses for other classes. Can the same or similar workaround be applied to MediaSource?

"Unexpected token ILLEGAL error" in vanilla setup on Windows

I'm happy to learn about this plugin as I need it for some work on getting custom elements V1 to work (without shadow DOM) across browsers.

I'm on Windows 10, Node v0.12.7, npm v4.1.1. I went forth with this environment to create the most vanilla setup in a new project. Devdependencies in my package.json:

 "devDependencies": {
    "babel-core": "^6.21.0",
    "babel-preset-env": "^1.1.8",
    "gulp": "^3.9.1",
    "gulp-babel": "^6.1.2"
  }

.babelrc file:

{
  "plugins": [
    "transform-custom-element-classes",
    "transform-es2015-classes"
  ]
}

gulpfile.js:

var gulp = require("gulp");
var babel = require("gulp-babel");

gulp.task("default", function () {
  return gulp.src("src/js/main.js")
    .pipe(babel())
    .pipe(gulp.dest("js"));
});

Running "gulp" in this basic setup leads to this blocking error:

const buildHelper = babelTemplate(`function CLASS() { return Reflect.construct
                                  ^
SyntaxError: Unexpected token ILLEGAL
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at W:\ce\node_modules\babel-core\lib\transformation\file\options\option-manager.js:174:20
    at Array.map (native)
    at Function.normalisePlugins (W:\ce\node_modules\babel-core\lib\transformation\file\options\option-manager.js:154:20)

The problem can be narrowed down to be caused by the transform-custom-element-classes plugin, because if I disable it in .babelrc, transpilation is succesful. The problem is also not related to the JS input file, since I get the same problem if I leave that totally blank.

Doing some digging around the web, sometimes these kind of errors can be caused by hidden characters copied in from another tool or web page, but I'm not seeing such hidden characters when I enable them in my IDE (Atom), so it's unlikely to be a cause.

I'm not sure the problem is due to Windows as a whole, or a specific combination in my setup. I did try to use the latest and most vanilla setup possible though.

HTMLElement is not defined - on babel compile

ReferenceError: HTMLElement is not defined

$ npm run dev

> [email protected] dev /Users/kristianmandrup/repos/cycle-apps/ce-cycle
> cross-env NODE_ENV=development babel-node .

[dev]
/Users/kristianmandrup/repos/cycle-apps/ce-cycle/src/js/other-elem.js:1
(function (exports, require, module, __filename, __dirname) { 'use strict';Object.defineProperty(exports,"__esModule",{value:true});function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&(typeof call==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}func

ReferenceError: HTMLElement is not defined
    at Object.<anonymous> (/Users/kristianmandrup/repos/cycle-apps/ce-cycle/src/js/other-elem.js:1:1028)

.babelrc file

{
	"presets": ["stage-0", "es2015"],
	"plugins": [
		"transform-custom-element-classes",
		"transform-es2015-classes"
	]
}

Babel modules loader config:

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

Any ideas? What am I missing in order for it to be "declared"?

Sub classing other html elements (HTMLButtonElement)

First off, thanks for your good work on this project - I was about to revert to es5 since Babel's default implementation doesn't work, but then I found this project and it works great!

I am curious if you've been able to pull off sub classing HTMLButtonElement (or any other element class besides HTMLElement). The code in this project ignores those classes - in my own testing it seems like chrome and Firefox both throw TypeError: Illegal constructor even if you use native classes instead of the babel compiled version.

Have you come across this? Any suggested workarounds? If so I'd be happy to help getting that into this babel plugin.

Add this behavior to Babel

I spoke with @hzoo at the recent Chrome Dev Summit afterparty about this issue, and we discussed updating the behavior in Babel to call Reflect.construct when extending exotic things like HTMLElement.

I was wondering if the maintainers of this project would be interested in helping put together a PR to explore updating Babel's behavior?

cc @owencm @justinfagnani

Block-scoped declarations syntax error

I have a simple custom element class that I am trying to transform with this plugin:

var owningDocument = document.currentScript.ownerDocument;
window.addEventListener('HTMLImportsLoaded', function(e) {
    class MyCustomElement extends HTMLElement {...
    }
    window.customElements.define('my-custom-element', MyCustomElement);
});

But I am getting a syntax error when using the plugin:

events.js:154
      throw er; // Unhandled 'error' event
      ^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

Here is my .babelrc file:

{
    "plugins": [
        "transform-custom-element-classes",
        "transform-es2015-classes"
    ]
}

Any ideas why this is happening?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.