Tuesday, August 23, 2016

Modern JS in a nutshell - ES6 Modules - Part 1 (What is ES6 Modules)



Recommended to read first posts :

- What is ECMAScript ? and the Relation Between ES and JavaScript
      http://blog.mohnady.com/2016/07/what-is-ecmascript-and-relation-between.html
- JavaScript Module Pattern & Closures: 
      http://blog.mohnady.com/2016/07/javascript-module-pattern-closures.html


- Current JavaScript does not have built-in support for modules,
JavaScript has had modules for a long time. However, they were implemented via libraries, not built into the language. ES6 is the first time that JavaScript has built-in modules.

But The most important work-arounds:
  - Old school Module Pattern Or Closure :
         http://blog.mohnady.com/2016/07/javascript-module-pattern-closures.html
  - CommonJS Modules
  - Asynchronous Module Definition (AMD)
         Writing Modular JavaScript With AMD, CommonJS & ES Harmony: https://addyosmani.com/writing-modular-js/


ES6 Modules to rescue:
- The new version of "EcmaScript 6" or "ES6", offers a number of new features that extend the power of the language.

ES 6 Modules Features
- Modules let you write componentized and shareable code.
- ES6 modules are stored in files. There is exactly one module per file and one file per module.
- Each module is a piece of code that is executed once it is loaded.
- A module can import things from other modules.
- This approach to modules avoids global variables

----------- Normal scripts versus modules -----------

Feature
Normal scripts 
ES6 Modules
Default mode
non-strict
strict
Top-level Variables
global   
local to module
Executed                 
synchronously   
asynchronously
ES6 Modules are singletons. Even if a module is imported multiple times, only a single “instance” of it exists.

----------------------------------------------------------------

- ES6 is not widely supported in today's browsers, so it needs to be transpiled to ES5.
       Transpiling : is a specific term for taking source code written in one language and transforming into another language that has a similar level of abstraction.

- ES6 Module Transpiler:
- You can choose between several transpilers.
The ES6 Module Transpiler is a tool that takes your ES6 module and compiles it into ES5 compatible code.
- We will Use Typescript
Install Using NPM -> "npm install -g typescript"
Compile           -> "tsc helloworld.ts"

-Note: TypeScript can be configured in two different ways: --target es6 or --target es5 --module commonjs.
  If TypeScript is set to target ES6 then it will output ES6 without transpilation. When set to target ES5 with CommonJS modules TypeScript will transpile your ES6 modules into a CommonJS format.

To be continued :)
#TecBites
#naadydev
#javascript



No comments: