What does babel's airbnb preset actually do? - javascript

I'm learning how to use webpack and babel to compile javascript for front-end applications, and I'm curious about the airbnb babel preset, which a lot of people seem to use when developing react applications. So a couple questions I have:
Does this preset translate any code into code which keeps to airbnb standards?
If so, is it necessary if I use the airbnb style guide anyways?
Additionally, I don't see why it is so necessary for someone who does not keep to the style. Does anyone ever read the compiled code (which is typically minified anyways)? In my experienced I've only read source code in their separate, original files. If that code is not already airbnb styled, I don't see what the advantage is of styling it in compilation -- at least for purposes of reading (I know some of the airbnb standards are for functionality, which does make sense).

A preset is a set of plugins used to support particular language features. You use presets to take advantage of the latest JavaScript features that haven't yet been implemented in browsers. Presets will transform your source code and syntax to be compatible with native JavaScript which browsers understand. For example, the
#babel/preset-react will allow you to write JSX (JavaScript as XML) style code, which is commonly used to define React components, although JSX isn't naturally understood by the browser.
So what's the deal with the babel-preset-airbnb preset?
Well AirBnb decided to create a guide to present a "reasonable approach to writing JavaScript" since everyone writes JavaScript differently. Ideally, this guide gives a greater sense of structure and order to JavaScript applications. The entire guidelines can be found here, where AirBnb describes their conventions or advice for writing more maintainable JavaScript.
So as for your question:
Does this preset translate any code into code which keeps to airbnb standards? If so, is it necessary if I use the airbnb style guide anyways?
Yes, the purpose of presets, in general, is to translate your code into industry standards currently understood by the browsers. So the preset provided by the AirBnb team will transpile your code according to their style guide mentioned above. As for the second part of your question, personally I would since they're good coding conventions and it's never a bad thing to write code the right way and have it stick to muscle memory.
Now as for why the code is minified?
Most people minify their JavaScript code prior to releasing to production to reduce the number of bytes needed to be downloaded by browser to run their web application. This is why when you inspect code most of the time it's minified code. With that being said, the whole purpose of their preset is to transpile your code into code that conforms to their style guidelines.

Related

What do those javascript front-end build tools mean when they say "compile" my js codes?

I saw those javascript front-end build tools, e.g. webpack, using the word "compile" from time to time. I am not sure what does compile javascript codes mean exactly, at least not like compile c/c++ codes.
I think I understand the "build" process in general, like bundle all js codes into one big file, minify/uglify the codes, using babel to transforms ES6 syntax(transpile). But what does compiling mean here, how does it fit in the whole building process or it is just another name for the whole build process?
Currently, I thought it may be just another name for using Babel to transforms ES6 syntax.
PS. after reading this SO Is Babel a compiler or transpiler? I believe my question is not same as that. Because it is not just related to Bable. For example, webpack also uses the term compiler https://webpack.js.org/api/compiler/ I do not understand its meaning there!
Browserify uses compiler as well e.g, https://github.com/robrichard/browserify-compile-templates "Compiles underscore templates from HTML script tags into CommonJS in a browserify transform"
It's better to describe the process as "transpilation."
Javascript always executes in a specific environment: in Chrome and Electron, it's the V8 engine; in Firefox, it's SpiderMonkey; etc. Each of these engines supports a specific set of language features and not others. As an example, some engines only support var and do not support const or let. Some support async/await, and others only support Promise.
But web developers know about these other features, and they want to use them, even when they're writing for an engine that doesn't support those features. Why? Most new language features are designed with the goal of making it possible to express complicated concepts in simpler and cleaner ways. This is extremely important, because the number one job of code is to make its purpose clear.
Thus, most language features are essentially syntactic sugar for existing functionality. In those cases, it's always possible to express a routine using both new and old syntax. This is a logical necessity.
A transpiler like Babel can read a script written using advanced syntax, and then re-express the script using a restricted set of language features. Relying on an intermediate representation called an abstract syntax tree, it can produce code that is guaranteed to be functionally equivalent, even though it does the work using very different, more widely-supported control structures.
Perhaps we web developers have gotten lazy in our terminology. When we talk of "compiling" javascript, we aren't usually talking about converting the script to something like bytecode. We're talking about transpilation.
Other kinds of build tasks are also becoming quite common. These days, the front-end is obsessed with a million flavors of "templating," because it's extremely tedious and confusing to describe DOM changes using pure javascript, and because application complexity is increasingly very rapidly. Some frameworks require you to convert source code to other intermediary forms that are later consumed by the web application at runtime. Others permit devs to describe UI using invented syntaxes that no browser is even attempting to support natively. Which tasks are needed varies by application depending on which frameworks are being used, the particulars of the application architecture, and the contours of the deployment environment, and that's just a start.
At its foundation, a web page is built using HTML, CSS, and javascript. That much hasn't changed. But today, most serious applications are built almost entirely in javascript (or something very much like it) and sass. Building the application is the process of applying a set of transformations to the source code to yield the final artifacts in those three bedrock languages.
We lump all that stuff under the term "compile."
You pretty much hit the nail on the head. When the Compile (or more appropriately transpilation) operation happens on a JavaScript project it can mean a number of things. As you mentioned these could range from minification, applying polyfills, shims, or the literal act of "compiling" the scripts into a single bundle file for platform/browser consumption.
Transpilation when using super sets of the JavaScript language such as TypeScript, ActionScript, or UnityScript describes the process of converting the source x-script back into native JavaScript which can be in turn be interpreted by a browser (since the browser doesn't recognize the superset languages).
However you are absolutely correct. We aren't compiling our JavaScript into binary, but the term gets thrown around a lot which can lead to confusion. All that said, we are closing in on the age of adoption of WebAssembly and ASMJs which promises to bring the age of bytecode running in the browser which will bring about some interesting possibilities, but alas... That's a story for another day ;)
You're right when you say these front-end Javascript tools don't use the word compile in same context in what your used to with build tools for languages like C/C++. C/C++ compilers turn source code into machine code.
These JavaScript build tools-- like Webpack-- use the word compile in a sense thats more metaphorical than conventional.
When web build tools use the word compile, they're using it in the sense that they are transpiling, minifying (a.k.a uglyfying), and bundling the source files so they are better optimized for client browsers and network requests. (Smaller file sizes, better browser compatibility, less HTTP requests from bundled assets, etc.)

TypeScript General Constructs reference guide

On the TypeScript GitHub page, there's a document that contains coding guidelines, explaining the do's and don't's of TypeScript: TypeScript Coding Guidelines. It says the following:
For a variety of reasons, we avoid certain constructs, and use some of our own. Among them:
Do not use ECMAScript 5 functions; instead use those found in core.ts.
Do not use for..in statements; instead, use ts.forEach, ts.forEachKey and ts.forEachValue. Be aware of their slightly different semantics.
Try to use ts.forEach, ts.map, and ts.filter instead of loops when it is not strongly inconvenient.
This makes sense to me. TypeScript obviously has a built-in library containing some ES5 functions optimised to be used within TypeScript. What I was wondering is if there's some kind of function reference like jQuery's own documentation, where each method has an explanation, example and other info regarding compatibility and version differences.
I've searched for this on the TypeScript website and on Google, but Google insists I'm searching for 'Generic Constructs' instead of 'General Constructs' (which Microsoft calls its built-in TS library). I can't really find anything related to the general constructs that they're talking about on the site, except for the core.ts file of course, which contains the general constructs.
Does anyone have a source I could use for this?
The coding guideline you refer to is the internal guideline for the TypeScript compiler project. It is not necessary the coding guideline of how you should write your project with TypeScript.
You should think of TypeScript as just JavaScript with a gradual type system.
The closer you keep your code close to JavaScript the better.
The TypeScript handbook would be a good starting point.
You can also check out the deep dive guide and other style guides available on GitHub.

Angular2 application half in Typescript and Javascript

I currently have a large JavaScript application with a lot of code written in vanilla Javascript for a specific platform for where I work.
I need to transform this into a web application I can open in the browser. This should be able to be done relatively easy by swapping out the components from my current application to the components of another web technology.
However since Angular2 is written in TypeScript, if I was to choose it as the framework I use, should I really also be rewriting the rest of my non-component JavaScript to TypeScript to or will I not need to do this.
Would it be a bad idea to have an application which was half TypeScript and half JavaScript like this?
It's not a bad idea to mix TypeScript and JavaScript. I do it every day. But you have to now that it may be very painful in some cases. So I can only advice to enforce migration to TypeScript as fast as possible.
I would suggest you to read this introduction to migration from JavaScript to TypeScript: https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html
This might also be a valuable source: https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html but I have the impression that the author has a very narrow opinion on how to work with typescript so just don't take everything there as it is, but just as a suggestion.
There are also a lot of other resources about migrating from JavaScript to TypeScript.
For the last month of migration to TypeScript I can say, that in many cases you can simply change your JavaScript to a TypeScript file and add exports. Than you need to add the needed imports in the other places and everything works just like before.
If you can make sure, that you only use old JavaScript in your TypeScript and not the other way round you can split your project into to packages. Load the JavaScript into global as done before and than create Typings for the parts of your JavaScript you use in TypeScript.

What are the main differences between Babel and TypeScript

I know that TypeScript was used to write Angular2, which probably makes it a better choice for someone who wants to get into Angular2, but when I look at Babel it looks very much like TypeScript.
I noticed that many well known companies stick to Babel.
Some questions:
What advantages do they have over each other?
Which make them better or worse choice for the project/developer?
What are the major differences between them and what make them unique?
TypeScript is a superset of JavaScript that compiles down into plain JavaScript (ES3+). The main goal of TypeScript is to enable developers to leverage excellent static typing capabilities. It is suitable for large applications that would benefit from features like:
Type annotations & type inference.
Generics.
Interfaces, enums, namespaces, modules and classes (the latter two available in ES6).
Safe refactoring.
As far as I am aware, Babel simply "transpiles" newer ECMAScript features down into a format that is supported by older ECMAScript environments. It is suitable for developers who want to write plain JavaScript using newer language features.
Victor Savkin one of angular 2 developers talks why they selected Typescript over other technologies.
http://victorsavkin.com/post/123555572351/writing-angular-2-in-typescript
the last section
Why Typescript?
"There are a lot of options available to frontend devs today: ES5, ES6 (Babel), TypeScript, Dart, PureScript, Elm, etc.. So why TypeScript?
Let’s start with ES5. ES5 has one significant advantage over TypeScript: it does not require a transpiler. This allows you to keep your build setup simple. You do not need to set up file watchers, transpile code, generate source maps. It just works. For many small projects this simplicity outweighs the advanced refactoring and navigation capabilities TypeScript provides. You just know where all the code is, and what it does.
ES6 requires a transpiler, so the build setup will not much different from TypeScript. But it is a standard, which means that every single editor and build tool either supports ES6 or will support it.
Elm and PureScript are elegant languages with powerful type systems that can prove a lot more about your program than TypeScript can. The code written in Elm and PureScript can be a lot terser than similar code written in ES5.
Each of these options has pros and cons, but I think TypeScript is in a sweet spot that makes it a great choice for most projects. TypeScript takes 95% of the usefulness of a good statically-typed language and brings it to the JavaScript ecosystem. You still feel like you write ES6: you keep using the same standard library, same third-party libraries, same idioms, and many of the same tools (e.g., Chrome dev tools). It gives you a lot without forcing you out of the JavaScript ecosystem."

What is the sturdiest way to get the closure compiler's type safety together with AMDs (requirejs)?

Although JavaScript and its many libraries (jQuery, RequireJS) allow for the creation of many great websites I find its lack of type safety daunting when contemplating building a larger website.
Google has a wonderful closure compiler which allows you to annotate your JavaScript with JSDoc and have it type check. Having experimented with its rich type system I expect this would greatly improve the maintainability of a longer lived JavaScript project.
The only problem is it doesn't play very nicely with AMD libraries like RequireJS. There is an experimental --transform_amd_modules flag that concatenates your JavaScript files and handles scoping by eliminating it. However this seems to be a bit of an anti-pattern, removing most of the benefits of RequireJS (but keeping the modular file structure). There's also the question of how much future support that will get
With the end goal being type-safety not at the expensive of RequireJS's benefits what would be my best bets?
PS: Although I've used RequireJS as the AMD library of choice I would not be against a solution that worked with a different AMD library.
Although the Closure Compiler may be used with various JavaScript libraries, the greatest benefit is achieved when used with the Closure Library, which has its own module and dependency system. Web applications using the Closure Library are generally compiled into one JavaScript file, which does not require asynchronous module loading. However, Closure does provide support for modules, which may be loaded asynchronously. Chad Killingsworth provided a good example of how to set up modules here. In addition, the plovr tool provides addition module support to simplify their usage.
If you have decided to use the Closure Compiler (and you are not tied to a large AMD codebase), you will likely maximize productivity by adopting the Closure Library and its module/dependency system in your new code. If you do plan to use an AMD codebase, then as you mentioned, the new experimental Compiler flags --transform_amd_modules and --process_common_js_modules may help, but when using unannotated libraries you miss out on much of the power of the Compiler.
Looking to the future, if ECMAScript Harmony modules become an official standard, then it is likely that libraries such as Closure, Dojo, and YUI will eventually conform to that standard. This might finally make it possible to seamlessly integrate JavaScript code from disparate libraries. In the meantime, if you want to write JavaScript applications and enjoy type checking, dead-code elimination, minification, advanced memory management, browser-agnosticism, and a phenomenal standard library, then I highly recommend using the Closure Compiler in conjunction with the Closure Library.

Categories

Resources