Use BabelJS only as a fallback for older browsers - javascript

I've integrated BabelJS into my workflow. This allows me to use ES6 features. I'm using gulp to convert my Javascript to ES5 Javascript.
I imagine that it would be better, though, to just use my ES6 code directly in newer browsers that support it. Is there a way to check for the availability of ES6 and use a BabelJS converted file only as a fallback?

Of course there is, but it's a lot of hard work. Similar approaches are being used to navigate a mobile client to a dedicated URL, but do you really want to start mapping each feature used in your code base, and then checking each and every feature in the client?
Stick with transpiling client code for now. It might be better in the future.

Related

How to figure out what Javascript methods/features/etc are available in ECMAscript 3.0

Hey I have an interesting question, I work with a platform that uses server-side javascript, but unfortunately this platform only supports ECMAscript 3.0. What's the easiest way for me to tell what arrays/methods are available for me to use within thi version?
I know some of the obvious things (i.e. arrow functions and most array methods), but i've definitely spent hours over code, wondering why it wasn't working in this platform, to figure out it's because i'm using an unsupported method.
MDN links are broken, ECMA official website seem to have the archives. Please check this pdf.
https://www.ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf
Online archives for all historical versions are available at this link
https://www.ecma-international.org/publications-and-standards/standards/ecma-262/
You can write your code with the most recent ES features and then use babel to transpile it to ES 3 before pushing to production. That's much easier than figuring out what you can use on ES 3.
I think there's a VS Code extension that simplifies the use of babel (similarly to what Live SASS Compiler does to convert SASS to CSS)

ES6 (ECMAScript 2015) support as of 2018

As a long time programmer just getting into JavaScript programming, I have the following questions that are still unclear despite having read many articles.
Looking at the ES6 (ECMAScript 2015) support by browsers, I can see that the supporting level is much less than that of Node.js, so the question is,
If both Node.js and browsers are using the modern V8 engine, why supporting level are so different?
Looking at the ES6 support in Node.js, I can see really really few ES6 features are unsupported now. However, what exactly does the supported means in the chart? I.e.,
Does it means even I write using the support ES6 features, I still need to use the Babel compiler to compile ES6 code to ES5 for Node.js to use it?
For TypeScript ES6-style JavaScript code that runs for Node.js, they are still need to be transpiled into an ES5 compatible form, despite that Node.js almost cover all ES6 featues, right? I.e.,
for the following code,
class Animal {
constructor(public name) { }
move(meters) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
console.log("Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
console.log("Galloping...");
super.move(45);
}
var sam = new Snake("Sammy the Python")
var tom: Animal = new Horse("Tommy the Palomino")
sam.move()
tom.move(34)
Does it need to be transpiled into an ES5 compatible form to runs with Node.js or not?
Finally, any online site that I can try playing with TypeScript/ES6 code like above?
I copy it to my chrome console, and got an error that I don't understand - Unexpected strict mode reserved word, and
I tried it on http://www.typescriptlang.org/play/index.html, but the console output is not working there.
Please help. thx.
Looking at the ES6 (ECMAScript 2015) support by browsers, I can see that the supporting level is much less than that of Node.js, so the question is,
Many different browsers and many different Javascript engines in them, each with their own level of ES6 support. The latest version of node.js is generally pretty up-to-date on what the V8 engine supports. Many browsers have longer release cycles and may not be as current, but each is different and has their own release strategy and level of ES6 support.
If both Node.js and browsers are using the modern V8 engine, why supporting level are so different?
If you compare the latest release of node.js with the latest release of Chrome on Windows, you won't see much difference in support. The ES6 support chart you're looking at seems old to me. For example, Chrome has had support for the Set object for a long time, but your chart says false.
Looking at the ES6 support in Node.js, I can see really really few ES6 features are unsupported now. However, what exactly does the supported means in the chart? I.e.,
Supported means you can use the feature directly without a transpiler, but how accurate that is depends upon the source of the document claiming it. Some documents do extensive testing of all the various edge cases of a given feature.
Others just look for general implementation. So if for example, you're looking at support for the Set object and it says "supported", then that is suppose to mean that you can just write plain Javascript that uses the Set object and it will just work. How accurate that document is depends upon the source of their data and the thoroughness of their testing.
Does it means even I write using the support ES6 features, I still need to use the Babel compiler to compile ES6 code to ES5 for Node.js to use it?
No. In a Javascript engine that supports a given feature in ES6, you can write ES6 code for that feature and directly run it in that Javascript engine. No transpiling is needed.
For TypeScript ES6-style JavaScript code that runs for Node.js, they are still need to be transpiled into an ES5 compatible form, despite that Node.js almost cover all ES6 featues, right? I.e.,
The class definitions you show are plain ES6 code. Those will work just fine as is in an ES6 capable Javascript engine.
If you write Typescript code, then you will have to transpile the TypeScript to Javascript because no Javascript engine (I know of) supports TypeScript directly. When transpiling form TypeScript to Javascript, you can usually specify whether you want the transpiler to generate ES5 compatible code (which will run in an ES5 engine or an ES6 engine) or ES6 compatible code (which will only run in an ES6 engine) depending upon what your target environment is capable of.
Does it need to be transpiled into an ES5 compatible form to runs with Node.js or not?
Your particular code appears to contain at least one TypeScript style variable declaration which would need to be transpiled. The rest looks like plain ES6 Javascript which should work in any ES6 engine without transpiling.
When I remove the TypeScript, fix some syntax errors in your code and implement the Animal constructor properly, then this code works fine in node.js v8.8.1 (which is what I currently have installed) and in Chrome 63.0.3239.132, Edge 41.16299.15.0 and Firefox 57.0.4 all on Windows 10:
// Generic ES6 code
class Animal {
constructor(name) {
this.name = name;
}
move(meters) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
console.log("Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
console.log("Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You can run this snippet yourself in any browser you desired to see the results (assuming the browser is modern enough to support a stack overflow snipppet). It works in all the current versions of browsers I have except IE 11.192.16299.0 (no surprise that IE doesn't support ES6).
I copy it to my chrome console, and got an error that I don't understand - Unexpected strict mode reserved word,
This happened to me when I tried to run your code in node.js until I removed the TypeScript from it so that it was just plain ES6. I think this particular error is caused by the public in this line:
constructor(public name) { }
since that is not part of the ES6 specification (it's apparently part of TypeScript).
It seems that there's one question you're dying to ask, but haven't exactly articulated is: "How do you know whether you have to transpile or not?".
The answer is that you have to understand the cross between the target environments you wish to run in and the newest features you plan to use. If you are writing server-side code that will only run in node.js, then it's a lot simpler. Examine a comprehensive table such as http://node.green/, study what it says for the node.js version you plan to use and the feature in question. If it indicates you should be able to use that feature, then write your code using that feature, write a test case for it and verify that both the code you wrote and the feature you are using both work. Add that to your body of knowledge about what you can and can't use in that version of node.js. You can then assume all future versions of node.js will also support that feature.
If you're writing code to run in a browser, life is much more complicated. If you plan to support a lot of browsers and really don't want to worry about ES6 support at all, then just transpile to an ES5 target and go about your business.
If you want to use non-transpiled code, then you have a lot of testing to do in a lot of browsers. You have to first specify exactly which versions of which browsers you are going to support and then you have to write your code and test cases and you have to test in every browser you plan to support. There really is no shortcut. When you find things that don't work, you'll have to either look for polyfills or work-arounds or stop using that ES6 feature.
Test the code in the environments that the code is going to be used in. Use the available means to implement the specific standard or specification within the environment that you are using the code at. Or try to create an approach yourself to resolve an issue that you encounter during development of your code while noting the progressions and persistent issue for others to be able to possibly address and resolve the issue, bug or requirement from their own perspective.
Simply due to the fact the a document states that the browser has implemented a specification or standard does not mean that the implementation is consistent with the specification, or implemented at all. The only way to verify whether a browser implements a standard is to test with code yourself. File issues and attempt to fix bugs yourself.
Browsers use different engines including Gecko, WebKit, not V8 alone; and can change over time in both name and implementations of specifications; see Monitor and potentially deprecate support for multitrack SourceBuffer support of 'sequence' AppendMode; How to use "segments" mode at SourceBuffer of MediaSource to render same result at Chomium, Chorme and Firefox?. There are many browsers. For example, Lynx does not use V8.
See web platform tests
The web-platform-tests Project is a W3C-coordinated attempt to build a
cross-browser testsuite for the Web-platform stack. Writing tests in a
way that allows them to be run in all browsers gives browser projects
confidence that they are shipping software that is compatible with
other implementations, and that later implementations will be
compatible with their implementations. This in turn gives Web
authors/developers confidence that they can actually rely on the Web
platform to deliver on the promise of working across browsers and
devices without needing extra layers of abstraction to paper over the
gaps left by specification editors and implementors.
For example, one test for Web Speech API, where volume property is specified as capable of being set, though was not able to detect a change of audio output for either Chromium or Firefox when setting the volume property of SpeechSynthesisUtterance to different values within the specified ranges.
Specifications are a totally different regime than actual browser implementations. Specifications or standards can be and are written well in advance of actual browser implementation, if implemented at all. You can use browserify, or write the code yourself to use NodeJS modules or other non-native code in the browser.

ES6 Proxy Polyfill for IE11

IE11 does not and will not implement ES2015 Proxy objects. Yet IE11's end of extended support is October 14, 2025.
Is there any way to polyfill Proxy objects for IE11? All other browsers support Proxy already.
If yes then we would all be able to use it in production today. If not then we'll have to wait almost a decade...
Edit: I'm asking specifically for IE11 as I know IE to usually have IE specific features that I'm often not aware of.
Edit2: I'm particularly interested in being able to implement a catch-all interceptor. Similar to __getattr__ in Python. It only has to work in IE11.
Best you can get is github: GoogleChrome/proxy-polyfill
According to Babel docs:
Due to the limitations of ES5, Proxies cannot be transpiled or polyfilled.
There's quite a concise answer for this question on Quora
Proxies require support on the engine level and it is not possible to polyfill Proxy.
Most major JS engines have yet to implement support. Check out the ECMAScript 6 compatibility table.
You may want to use Object.observe instead, possibly with polyfills for browsers other than Chrome, but even then the proposal has been withdrawn, and it has been announced it will be removed from Chrome in a future version.
I personally haven't tried the Object.observe solution but it might be a good place to start.
Good luck!
EDIT:
Thank you to Matt Jensen in the comments for pointing out there is infact a way to polyfill some parts of ES6 Proxy using this package: github.com/GoogleChrome/proxy-polyfill
AWESOME
Direct solution for polyfilling ES6 Proxy in environments without support this feature, of course is impossible - if storing some polyfill function info window.Proxy is meant. But if thinking this way, most modern features of ES6 can't be supported, because they will raise syntax error for old-version ECMAScript engine.
That's why you should use transpiler, which perform preceding wrapping ES6 code into specific constructions, and then evaluate transformed code on old engine. In current case, just use one Babel plugin: https://www.npmjs.com/package/babel-plugin-proxy
Of course, while using this solution, you should configure Webpack to segregate target bundles for different client agents / browsers, depending on it's feature set discovery. See details here: https://gist.github.com/newyankeecodeshop/79f3e1348a09583faf62ed55b58d09d9

How to safely use ES6 new features?

There are many ES6 features that look great like => syntax, Map object, and a long etc.
To be honest I'm kind of tired of checking if there is support for addEventListener due to ie8 attachEvent, and I wouldn't like that kind of pain coming back to my life.
So how, would you deal with this new posibilities? (or how will you, lets say, in a year or so). Would you not use them for basic actions but to add another layer of extra functions? Would you use it just for apps that you know you will be running in browsers that support them? Would you wait untill there is at least 90% of support?
I understand these are great features but for short to medium term usage it seems that you'd need to double your code checking and fallbacking for support.
Any enlightment about this subject?
EDIT: Please, don't mark this as duplicate. Notice I'm not asking how to check for support, I'm asking if it is wise to start using it, or it is better to wait. I'm also asking if the support check is the best option, not how to do it, or if there are other ways to proced while designing your code.
tl;dr: Make use of transpilers and polyfills.
Whether or not you should use new features primarily depends on your target environment and how exactly you are using new features. E.g. if you are targeting only the latest browser version, then you won't have an issue. Have to support IE8? That could be more difficult.
In general though, you should start using new features as soon as possible, and make use of tools that help you with that.
There are two aspects to look at:
New APIs
New syntax constructs
APIs
New API's can often (but not always) be polyfilled. I.e. you include a library which checks whether certain parts of the API exist, e.g. Map, and provides an alternative implementation if it doesn't.
These alternative implements may not be 100% equivalent or may not be as performant as a native implementation, but I'd say they work for 95% for all use cases.
The nice thing about polyfills is that you will be automatically using the native browser implementation if it is available.
Syntax
Making use of new syntax constructs, such as arrow functions or classes, is a bit more complex (but not much). The biggest issue is that browsers who do not support the syntax cannot even evaluate your code. You can only send code to the browser that it can actually parse.
Fortunately many of the new syntax elements, such as arrow functions, are really just syntactic sugar for things that are already possible ES5. So we can convert ES6 code into their ES5 or even ES3 equivalent.
Several such tools, called transpilers, have emerged over the last one or two years. Note that the transpiler has to convert your code before it is sent to the browser. This means that instead of simply writing your JS file and directly include in your page, you need to have a build step that converts the code first (just like we have in other languages, like C or Java).
This is different from how we wrote JS a couple of years ago, but having a build step has become increasingly more accepted by the JS community. There are also many build tools that try to make this as painless as possible.
One drawback is, unlike with polyfills, that you won't magically be using the native features if they become available. So you could be stuck with shipping the transpiled version for a long time, until all your target environments support all the features you need. But that's probably still better than not using the new features at all.
You can use BabelJS or Google Traceur
You have to include in your build process a step to transform ES6, ES7 code to Javascript compatible with todays browsers. Like a gulp or grunt task. Babel has a list of supported tools here

Is there a reset.js similar to a reset.css?

Reset.css files are used to resolve browser inconsistencies when it comes to styling.
Is there something similar for JavaScript inconsistencies across browsers like a reset.js?
For example this "reset.js" library would define a prototype for the String trim() method as specified in this question since (among other things) IE8 does not support this.
I know libraries like jQuery can be used to overcome these inconsistencies but having something like a reset.js could help when using 3rd party JavaScript libraries that do not use jQuery.
Yes, there are polyfills to do exactly that. But there are so many things you'd need to fix that you can't put all fixes in one single script :-)
Have a look at the HTML5 Cross Browser Polyfills list.
If you're specifically interested in EcmaScript compliance, there are ES5 shims to retrofit missing or incorrectly implemented methods like String::trim; yet they can't fix the engine bugs (identifier-keywords, NFEs, …).
I don't know of one that is/does exactly what you asked in a single library and as far as I know there are quite a lot of people against 'patching' the built in JavaScript objects, and some libraries (e.g. ExtJS) that did this in previous versions have changed and do now deliver the functionality in custom utility functions.
On the other hand there are a ton of smaller and larger shims to bring missing functionality to older browser, especially dealing with HTML5 inconsistencies.

Categories