I am learning typescript, I have a simple code that creates a constant variable and prints it.
const versionNuber : number = 1.3;
console.log(versionNuber);
and after running a command tsc on the file generates following javascript code.
var versionNuber = 1.3;
console.log(versionNuber);
My question is how to transpile the constant to javascript?
Why tsc doesn't do that even though const is supported in javascript?
In the compiler options, there is a target option, which indicates the target language version to transpile the Typescript to. It defaults to ES3 (standardized in 1999; compatible with basically everything).
If you want to keep const from being turned into var, set the target to ES2015 or later. (const was not officially supported in JS before ES2015 - using it will throw in IE10, for example, which was released in 2012)
Playground link with ESNext target showing const being preserved
Related
I want to ensure that my output only contains "vanilla" javascript and does not contain new features (like const, map(), => etc.).
This is to ensure that the code still works on legacy browsers.
I have the following code that basically gets some JSON data, looks for the keys with "servergenre", and saves the results in an array.
This is a follow up of this question.
let result = [];
Object.keys(data).forEach( key => {
if(/servergenre/.test(key)){
result.push(data[key])
}
});
Even though the code is working correctly, in some editors it raises syntactic errors:
"key": unsolvable variable or type key
"=>": expression expected
"if( / server...": formal parameter name expected
")){": , expected
"});": statement expected
Here is an image to show you where the errors are:
As I said the code is working fine, I just need it to be fixed or another approach to get rid of the errors.
Furthermore, many compressors and minifiers do not support this bit of code. So I can’t minify it.
Thanks in advance.
ES2015, formerly known as ES6, is a more recent version of JavaScript, which introduces features such as the => syntax for functions you are using.
Not all features of ES2015 are fully supported in all browsers, so many people who use it pass it through a compiler (“transpiler”) first to convert it to ES5, which is supported by all browsers. Babel is one such transpiler. But if you are only targeting newer browsers, that would explain why the => syntax is working for you.
You just need to change your editor settings to understand that syntax. Exactly how you do that depends on what text editor you are using. It could be that your editor's built-in JavaScript mode doesn't know how to read ES2015 syntax, and you need to either upgrade your editor or install a third-party plugin that provides an updated error-checker. Or it could be that your editor supports both ES5 and ES2015, and it thinks you are trying to write your project only in ES5. In this case you just need to go to the settings and tell your editor that you mean for this project to use ES2015 (or ES2016, which is currently the most recent version).
Fat arrows are ES6 syntax. If that causes trouble, just write good old ES5 :
let result = [];
Object.keys(data).forEach( function(key) {
if(/servergenre/.test(key)){
result.push(data[key])
}
});
Experimenting with destructuring and found that the same code works on stackoverflow and not Codepen (toy gets "undefined"): http://codepen.io/tsalexey544/pen/VjWxmm?editors=0010#
What does it mean? should I worry when using destructuring in my projects?
let obj = {
species: "Cat",
// toy: "ball",
}
function whatDoTheyDo ({species, toy = "ball"}) {
return `The ${species} playes with a ${toy}`
}
document.write(whatDoTheyDo(obj));
You just need to set the Preprocessor to babel in CodePen, otherwise it will use standard ES5, where destructuring is not supported.
If you want to use ES6/ES7 features you have to "transpile" your code back to ES5 using certain tools such as Babel. Some browsers already support some ES6 features, but full support is still somehow spotty.
Edit - To answer your question: YES, you should worry about serving valid ES5 code, since ES6 is not yet fully supported. At the very minimum you should feed your code to Babel and publish the resulting code, but I strongly suggest looking it Webpack and going for a full toolchain
I understand that the const keyword has been already implemented across the board in browsers except for IE10 versions, but is it viable? If someone jumps on my site on IE10< will the "const" keyword be re-assigned to "var"? if not will the whole site fail? the MDN docs on the const keyword give a handy chart at the bottom which tells me that not only IE, but rather many Mobile browsers do not support it either. should i just scrap it and use var?
Take Babel, the ECMAScript 2015 (ES6) to ECMAScript 5 transpiler.
If you write:
const a = 123;
It outputs:
"use strict";
var a = 123;
If the potential of breaking your code on unsupported browsers isn't enough, i think that should be.
IE11 and above supports const but IE10 and below do not.
If you attempt to use const in any browser that does not support it, you will get a syntax error. If you must support older browsers, you cannot use const unless you use a transpiler to compile your code down into ES5. Babel is a good example of such a transpiler.
If you want to write clean ES6 (ES2015) code using const you could use JS compiler like Babel. For example:
const a = 1;
it recompile to
"use strict";
var a = 1;
If you want painless babel configuration use this yeoman babel generator.
I'm trying to use default parameter values, but getting this error:
SyntaxError: Unexpected token =
Is this working in node now? I'm using 5.9.1
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters
I also tried messing with passing flags to node without success.
node --harmony_default_parameters
It seems like a basic part of ES6 so hope it would be working by now!
Is this working in node now?
Not yet. It's only available for testing under a flag. V8 v4.9 (released in Chrome 49) is the earliest stable version of V8 that supports default parameters. Nodejs v5.9.1 runs on top of V8 v4.6.85.31. You can use the command node -p process.versions.v8 for checking the current V8 version. Also, you have to wait until Nodejs v6.x for a complete support of default parameters. You can see this issue for more details.
The problem seems to be a result of mixing ES6 style functions:
getReply: (input, userId = null) => { // No good
getReply: function(input, userId = null) { // OK
You can find the list of what ES6 features are currently supported by Node here. As it stands, it doesn't look like default paremeters are implemented, or at least not fully.