Introduction to ECMAScript 6
ECMAScript 6.0 (hereafter referred to as ES6) is the next generation standard for the JavaScript language and has been officially released in June 2015. Its goal, to make the JavaScript language available for writing complex and large applications, is to become an enterprise-level development language.
standard of The framers have a plan, Standards to be issued annually thereafter, Use year as version。 owing toES6 of The first version is (located) at2015 Year released of, So also known asECMAScript 2015( acronymES2015)。
2016 year6 month, Minor amendments of《ECMAScript 2016 standard》( acronym ES2016) Posted as scheduled。 Due to very minor changes( Only new array instances were added ofincludes approach harmony exponential operator), therefore ES2016 together with ES2015 It's basically the same standard, Both are seen as ES6。 According to the plan,2017 year6 To be released in January ES2017。
A common question is, what exactly is the relationship between ECMAScript and JavaScript?
To make this clear, one needs to look back at history. In November 1996, Netscape, the creator of JavaScript, decided to submit JavaScript to the international standardization organization ECMA in the hope that the language would become an international standard. The following year, ECMA published the first version of the standard document 262 (ECMA-262), which specifies a standard for browser scripting languages and calls this language ECMAScript, and this version is version 1.0.
The standard was developed for the JavaScript language from the beginning, but there are two reasons why it is not called JavaScript. One is a trademark; Java is a trademark of Sun, and under the license agreement, only Netscape can legally use the name JavaScript, and JavaScript itself has been registered as a trademark by Netscape. Secondly, I wanted to reflect that the language was developed by ECMA, not Netscape, so as to help ensure the openness and neutrality of the language.
therefore,ECMAScript harmonyJavaScript of The relationship is, The former is the latter of specifications, The latter is the former of A way to achieve( additionally ofECMAScript The dialect also hasJscript harmonyActionScript)。 Daily occasions, The two words are interchangeable of。
The ES6 took a full 15 years from the start of its development to its final release.
As mentioned earlier, ECMAScript 1.0 was released in 1997, and the next two years saw the successive releases of ECMAScript 2.0 (June 1998) and ECMAScript 3.0 (December 1999). 3.Version 0 was a huge success, gaining widespread support in the industry and becoming the prevailing standard, laying down the basic syntax of the JavaScript language, which was fully inherited by subsequent versions. To this day, the moment a beginner starts learning JavaScript, they are actually learning the syntax of version 3.0.
2000 year,ECMAScript 4.0 It's starting to brew.。 This version didn't end up passing, but it of Most of the content wasES6 Inherited。 therefore,ES6 develop of The starting point is actually2000 year。
Why didn't the ES4 pass? Because this version was so radical, a radical upgrade to ES3, it caused some members of the standards committee to be reluctant to accept it. ECMA's Technical Committee 39 (TC39) is responsible for developing the ECMAScript standard, with members including Microsoft, Mozilla, Google and other major companies.
In October 2007, a draft of ECMAScript version 4.0 was released, and the official version was expected to be released the following August. However, there is a serious disagreement among the parties as to whether to adopt this standard. The big companies, led by Yahoo, Microsoft, and Google, oppose a major upgrade of JavaScript and advocate minor changes; Mozilla, led by Brendan Eich, the creator of JavaScript, sticks with the current draft.
In July 2008, because there was too much disagreement and too much debate about what features should be included in the next version, ECMA met and decided to suspend the development of ECMAScript 4.0, releasing a small part of it involving improvements to existing features as ECMAScript 3.1, and expanding the scope of other radical ideas into a later version, which was given the project code name Harmony due to the atmosphere of the meeting. Shortly after the meeting, ECMAScript 3.1 was renamed ECMAScript 5.
In December 2009, ECMAScript version 5.0 was released. The Harmony project was split in two, with some of the more viable ideas named JavaScript.next continuing to be developed, which later evolved into ECMAScript 6; some of the less mature ideas were considered JavaScript.next.next and will be considered for release further down the line. The general consideration of the TC39 committee was that ES5 would remain largely compatible with ES3, and that the larger syntax fixes and new features added would be done by JavaScript.next. At the time, JavaScript.next referred to ES6, and since the release of version 6, it refers to ES7. TC39's judgment is that ES5 will become the dominant standard for JavaScript development by the middle of 2013 and remain in that position for five years thereafter.
In June 2011, ECMAscript version 5.1 was released and became an ISO International Standard (ISO/IEC 16262:2011).
In March 2013, the ECMAScript 6 draft was frozen and no new features were added. The new features are envisioned to be put into ECMAScript 7.
2013 year12 month,ECMAScript 6 Draft release。 And then there's12 months of discussion period, Listen to feedback from all parties。
In June 2015, ECMAScript 6 was officially adopted as an international standard. Fifteen years have passed at this point, counting from the year 2000.
Major browsers of latest version, rightES6 of Support can be viewedkangax.github.io/es5-compat-table/es6/ . Support has grown over time, and most of the features of ES6 are implemented.
Node.js is the server runtime environment for the JavaScript language and has more support for ES6 than the browser. With Node, experience more ES6 features. Version management tools are recommendednvm , to install Node, as the version can be switched freely. However.nvm No supportWindows system, If you use theWindows system, following of The operation can be changed tonvmw perhapsnvm-windows Substitute.
erectnvm Need to open a command line window, Run the following of command。
$ curl -o- https://raw.githubusercontent.com/creationix/nvm/<version number>/install.sh | bash
The above command ofversion number where it needs to be replaced with the version number. The version number at the time of writing of this section isv0.29.0 . After this command is run, thenvm will be installed by default in the user home directory of the.nvm Subdirectory.
Then, activate thenvm。
$ source ~/.nvm/nvm.sh
After activation, install the latest version of Node.
$ nvm install node
After the installation is complete, switch to that version.
$ nvm use node
Use the following command to see all the ES6 features that Node has implemented.
$ node --v8-options | grep harmony --harmony_typeof --harmony_scoping --harmony_modules --harmony_symbols --harmony_proxies --harmony_collections --harmony_observation --harmony_generators --harmony_iteration --harmony_numeric_literals --harmony_strings --harmony_arrays --harmony_maths --harmony
The output of the above command will vary depending on the version.
I wrote one.ES-Checker module, Used to check the impact of various operating environments onES6 of Status of support。 interviewsruanyf.github.io/es-checker, You can see your of Browser SupportES6 of degree (level or extent)。 Run the following of command, You can see what you are (located) at use ofNode environmental impact onES6 of Level of support。
$ npm install -g es-checker $ es-checker ========================================= Passes 24 feature Dectations Your runtime supports 57% of ECMAScript 6 =========================================
Babel is a widely used ES6 transcoder that converts ES6 code to ES5 code for execution in existing environments. This means that you can write programs in the ES6 way without having to worry about whether your existing environment supports it. Here's an example.
// before transcoding input.map(item => item + 1); // After transcoding input.map(function (item) { return item + 1; });
on top of of The original code used the arrow function, This feature is not yet widely supported,Babel Converting it to a normal function, will be able to (located) at currently available ofJavaScript The environment is implemented。
Babel of The configuration file is.babelrc , which is stored in the root directory of the project. The first step in using Babel is to configure this file.
This file is used to set up transcoding rules and plugins in the following basic format.
{ "presets": [], "plugins": [] }
presets Field setting transcoding rules, Officials offer the following of ruleset, You can install as many as you need。
# ES2015 transcoding rules $ npm install --save-dev babel-preset-es2015 # react transcoding rules $ npm install --save-dev babel-preset-react # Transcoding rules for different phases of ES7 syntax proposals (there are 4 phases), optionally one $ npm install --save-dev babel-preset-stage-0 $ npm install --save-dev babel-preset-stage-1 $ npm install --save-dev babel-preset-stage-2 $ npm install --save-dev babel-preset-stage-3
Then, add these rules to the.babelrc。
{ "presets": [ "es2015", "react", "stage-2" ], "plugins": [] }
note, All of the followingBabel tools harmony modular use, It all has to be written first.babelrc。
Babel offersbabel-cli tool for command line transcoding.
it of The installation command is as follows.
$ npm install --global babel-cli
The basic usage is as follows.
# Transcoding results to standard output $ babel example.js # Transcoding results to a file # --out-file or -o parameter specifies the output file $ babel example.js --out-file compiled.js # Or $ babel example.js -o compiled.js # Whole directory transcoding # --out-dir or -d parameter specifies the output directory $ babel src --out-dir lib # Or $ babel src -d lib # -s parameter to generate source map file $ babel src -d lib -s
The code above is (located) at in a global environment, carry outBabel encoding。 This means that, If the project is to run, The global environment must haveBabel, This means that the project generates environmental of depend on。 on the other hand So. Do also cannot support the use of different versions for different projects ofBabel。
One solution would be to convert thebabel-cli Installed in the project.
# Installation $ npm install --save-dev babel-cli
Then, rewritepackage.json。
{ // ... "devDependencies": { "babel-cli": "^6.0.0" }, "scripts": { "build": "babel src -d lib" }, }
encoding of length of time, Just execute the following of command。
$ npm run build
babel-cli The tool comes with ababel-node command, Provide a supportES6 ofREPL environments。 It supportsNode ofREPL environments of All features, And it can run directlyES6 code。
It does not have to be installed separately, but comes withbabel-cli Installed together. Then, executebabel-node Just enter the REPL environment.
$ babel-node > (x => x * 2)(1) 2
babel-node command to run ES6 scripts directly. Put the above code into the script filees6.js And then Run directly。
$ babel-node es6.js 2
babel-node It can also be installed in the project.
$ npm install --save-dev babel-cli
Then, rewritepackage.json。
{ "scripts": { "script-name": "babel-node script.js" } }
In the code above, the use ofbabel-node replacenode So.script.js There is no transcoding to be done per se.
babel-register Module Rewritingrequire command, adding a hook to it. Thereafter, whenever usingrequire loaded.js、.jsx、.es harmony.es6 The file with the suffix name will then be transcoded with Babel first.
$ npm install --save-dev babel-register
When used, Must first loadedbabel-register。
require("babel-register"); require("./index.js");
Then, there is no need to manually make any changes to theindex.js Transcoded.
It is important to note thatbabel-register It's only for therequire command loaded of file transcoding, and will not transcode the current file。 additionally, As it is transcoded in real time, So only suitable for (located) at Development environment use。
If some code needs to call Babel's API for transcoding, use thebabel-core Module.
The installation command is as follows.
$ npm install babel-core --save
Then, in the project, you can call thebabel-core。
var babel = require('babel-core'); // String transcoding babel.transform('code();', options); // => { code, map, ast } // File transcoding (asynchronous) babel.transformFile('filename.js', options, function(err, result) { result; // => { code, map, ast } }); // Document transcoding (synchronization) babel.transformFileSync('filename.js', options); // => { code, map, ast } // Babel AST transcoding babel.transformFromAst(ast, code, options); // => { code, map, ast }
Configuration objectsoptions You can refer to the official documentationhttp://babeljs.io/docs/usage/options/。
Here's an example.
var es6Code = 'let x = n => n + 1'; var es5Code = require('babel-core') .transform(es6Code, { presets: ['es2015'] }) .code; // '"use strict"; var x = function x(n) { return n + 1; };'
In the code above, thetransform approach of The first parameter is a string, Indicates that it needs to be converted ofES6 code, The second argument is the conversion of Configuration objects。
Babel Only new ones are converted by default ofJavaScript syntax(syntax), without converting new ones ofAPI, Like whatIterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise and other global objects, and some definitions (located) at On the global object of approach( Like whatObject.assign ) Neither will transcode.
As an example, the ES6 is available inArray A new object has been added to theArray.from Methods. Babel would not transcode this method. If you want this method to run, you must use thebabel-polyfill that provides a shim for the current environment.
The installation command is as follows.
$ npm install --save babel-polyfill
Then, in the head of the script, add the following line of code.
import 'babel-polyfill'; // perhaps he who require('babel-polyfill');
The list of APIs that Babel does not transcode by default is extensive and can be viewed in detailbabel-plugin-transform-runtime modulardefinitions.js Document.
Babel It can also be used Browser Environment。 But, fromBabel 6.0 Begin, The browser version is no longer available directly, It's about building with build tools。 If you don't have perhaps Don't want to use the build tool, This can be done by installing the5.x version ofbabel-core Module Access.
$ npm install babel-core@5
Run the above of After the command, will be able to (located) at Current Catalog ofnode_modules/babel-core/ Inside the subdirectory, find thebabel of The browser versionbrowser.js( Not streamlined) harmonybrowser.min.js (Streamlined).
And then, will be below of The code is inserted into the Web page。
<script src="node_modules/babel-core/browser.js"></script> <script type="text/babel"> // Your ES6 code </script>
In the code above, thebrowser.js be Babel offers of Converter script, OK (located) at The browser runs。 user ofES6 Script put (located) atscript Among the tags, but specifytype="text/babel"。
Another method is to use thebabel-standalone Modules are available of The browser version, Insert it into a Web page。
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.4.4/babel.min.js"></script> <script type="text/babel"> // Your ES6 code </script>
note, Web pages will be in real timeES6 Code toES5, There will be an impact on performance。 The production environment requires loaded It's been transcoded. of Script.
Here's how to package the code so that the browser can use it of script, withBabel matchBrowserify As an example. First, install thebabelify Module.
$ npm install --save-dev babelify babel-preset-es2015
And then, Use again Command line conversionES6 Script.
$ browserify script.js -o bundle.js -t [ babelify --presets [ es2015 ] ]
The code above takes the ES6 scriptscript.js tobundle.js , the browser loads the latter directly and it's fine.
(located) atpackage.json Set up the following code so you don't have to enter parameters every time you go to the command line.
{ "browserify": { "transform": [["babelify", { "presets": ["es2015"] }]] } }
Babel provides a REPL online compiler , you can convert ES6 code to ES5 code online. The converted code can be inserted and run directly as ES5 code on a web page.
Many tools require Babel for pre-coding, here are two examples: ESLint and Mocha.
ESLint is used to statically check the syntax and style of the code and the installation command is as follows.
$ npm install --save-dev eslint babel-eslint
Then, in the root of the project, create a new configuration file.eslintrc by adding to itparser Fields.
{ "parser": "babel-eslint", "rules": { ... } }
again (located) atpackage.json in the middle, Join accordingly ofscripts Script.
{ "name": "my-module", "scripts": { "lint": "eslint my-files.js" }, "devDependencies": { "babel-eslint": "...", "eslint": "..." } }
Mocha is a test framework, If you need to perform useES6 grammar of Test the script, Can be modifiedpackage.json ofscripts.test。
"scripts": { "test": "mocha --ui qunit --compilers js:babel-core/register" }
In the above order, the--compilers parameter specifies the transcoder for the script, specifying a suffix ofjs documents, all of which require the use ofbabel-core/register Transcode first.
Google firm ofTraceur A transcoder that also converts ES6 codes to ES5 codes.
Traceur Allow willES6 code Direct web page insertion。 First of all, Have to (located) at Page header loadedTraceur warehouse Document.
<script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script> <script src="https://google.github.io/traceur-compiler/bin/BrowserSystem.js"></script> <script src="https://google.github.io/traceur-compiler/src/bootstrap.js"></script> <script type="module"> import './Greeter.js'; </script>
In the code above, there are fourscript label。 The first one is loadedTraceur of library file, second reason harmony The third is to use this library file for Browser Environment, And the fourth is loaded User script, This script can be used insideES6 code。
Note that the fourthscript taggedtype The value of the attribute ismodule Instead oftext/javascript . This is a flag for the Traceur compiler to recognize ES6 code, and the compiler will automatically put alltype=module of The code is compiled asES5 And then Then leave it to the browser to execute。
In addition to referencing external ES6 scripts, it is also possible to place ES6 code directly in the web page.
<script type="module"> class Calc { constructor(){ console.log('Calc constructor'); } add(a, b){ return a + b; } } var c = new Calc(); console.log(c.add(4,5)); </script>
Normally, the above code would print 9 on the console.
If you want to have precise control over Traceur's behavior, you can use the following parameter configuration writeup.
<script> // Create the System object window.System = new traceur.runtime.BrowserTraceurLoader(); // Set some experimental options var metadata = { traceurOptions: { experimental: true, properTailCalls: true, symbols: true, arrayComprehension: true, asyncFunctions: true, asyncGenerators: exponentiation, forOn: true, generatorComprehension: true } }; // Load your module System.import('./myModule.js', {metadata: metadata}).catch(function(ex) { console.error('Import failed', ex.stack || ex); }); </script>
In the above code, the global object of Traceur is first generatedwindow.System And thenSystem.import Methods can be used loadedES6 Module. loaded of length of time, One needs to be passed in Configuration objectsmetadata , the object'straceurOptions property can be configured to support ES6 functionality. If set toexperimental: true, that means nothing butES6 beyond, Some experimental support is also supported of New features。
Traceur also offers a Online compiler , you can convert ES6 code to ES5 code online. The converted code can be inserted and run directly as ES5 code on a web page.
The above example converted to run as ES5 code looks like the following.
<script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script> <script src="https://google.github.io/traceur-compiler/bin/BrowserSystem.js"></script> <script src="https://google.github.io/traceur-compiler/src/bootstrap.js"></script> <script> $traceurRuntime.ModuleStore.getAnonymousModule(function() { "use strict"; var Calc = function Calc() { console.log('Calc constructor'); }; ($traceurRuntime.createClass)(Calc, {add: function(a, b) { return a + b; }}, {}); var c = new Calc(); console.log(c.add(4, 5)); return {}; }); </script>
When used as a command line tool, Traceur is a Node module that first needs to be installed with Npm.
$ npm install -g traceur
Once installed successfully, Traceur can be used from the command line.
Traceur runs the es6 script file directly, which will display the results of the run in the standard output, starting with the previouscalc.js As an example.
$ traceur calc.js Calc constructor 9
If you want toES6 The script turns toES5 Save, To use below of orthography。
$ traceur --script calc.es6.js --out calc.es5.js
The above code for the--script option indicates that the input file is specified.--out The option represents the specified output Document.
To prevent some features from not compiling successfully, it is best to add--experimental Options.
$ traceur --script calc.es6.js --out calc.es5.js --experimental
Command line conversion generates of documents, You can just put it in your browser and run it。
Traceur ofNode.js The usage is as follows( Assumes installation oftraceur module)。
var traceur = require('traceur'); var fs = require('fs'); // Converting ES6 scripts to strings var contents = fs.readFileSync('es6-file.js').toString(); var result = traceur.compile(contents, { filename: 'es6-file.js', sourceMap: true, // Other settings modules: 'commonjs' }); if (result.error) throw result.error; // result object ofjs The property is after conversion ofES5 code fs.writeFileSync('out.js', result.js); // The sourceMap attribute corresponds to the map file fs.writeFileSync('out.js.map', result.sourceMap);
In March 2013, the draft of ES6 was closed and no more new features were accepted. New features will be added to ES7.
Anyone can propose to TC39, and there are five stages from proposal to becoming a formal standard. Changes at each stage will need to be approved by the TC39 Committee.
A proposal that makes it to Stage 2 is pretty much the same as being sure to be included in ES7.
This book of One of the goals of writing, Is trackingECMAScript language of Latest developments。 For those clear of、 perhaps is very promising to includeES7 of function, Especially thoseBabel Supported of function, will be introduced。
This book is about ofES7 The list of features is below。
Stage 0:
Stage 1:
Stage 2:
Stage 3
Stage 4:
ECMAScript current of All proposals, OK (located) atTC39 of Official websiteGithub.com/tc39/ecma262 View.
The Babel transcoder can use the syntax of individual stages by installing and using plugins.