检测Node.js是否支持ES6

1,140 阅读1分钟

如果读者安装的Node.js版本较新,则可以支持大量的JavaScript ES6语法;如果版本太旧并且无法升级,那么该如何检测其是否支持这些新的语法?

这里推荐使用es-checker来检测当前Node.js对ES6的支持情况。使用如下命令安装es-checker:

npm install -g es-checker

安装后,使用命令es-checker检测当前Node.js的版本支持情况,结果如下图:


~ % es-checker

ECMAScript 6 Feature Detection (v1.4.2)

Variables

  √ let and const

  √ TDZ error for too-early access of let or const declarations

  √ Redefinition of const declarations not allowed

  √ destructuring assignments/declarations for arrays and objects

  √ ... operator

Data Types

  √ For...of loop

  √ Map, Set, WeakMap, WeakSet

  √ Symbol

  √ Symbols cannot be implicitly coerced

Number

  √ Octal (e.g. 0o1 ) and binary (e.g. 0b10 ) literal forms

  √ Old octal literal invalid now (e.g. 01 )

  √ Static functions added to Math (e.g. Math.hypot(), Math.acosh(), Math.imul() )

  √ Static functions added to Number (Number.isNaN(), Number.isInteger() )

String

  √ Methods added to String.prototype (String.prototype.includes(), String.prototype.repeat() )

  √ Unicode code-point escape form in string literals (e.g. \u{20BB7} )

  √ Unicode code-point escape form in identifier names (e.g. var \u{20BB7} = 42; )

  √ Unicode code-point escape form in regular expressions (e.g. var regexp = /\u{20BB7}/u; )

  √ y flag for sticky regular expressions (e.g. /b/y )

  √ Template String Literals

Function

  √ arrow function

  √ default function parameter values

  √ destructuring for function parameters

  √ Inferences for function name property for anonymous functions

  × Tail-call optimization for function calls and recursion

Array

  √ Methods added to Array.prototype ([].fill(), [].find(), [].findIndex(), [].entries(), [].keys(), [].values() )

  √ Static functions added to Array (Array.from(), Array.of() )

  √ TypedArrays like Uint8Array, ArrayBuffer, Int8Array(), Int32Array(), Float64Array()

  √ Some Array methods (e.g. Int8Array.prototype.slice(), Int8Array.prototype.join(), Int8Array.prototype.forEach() ) added to the TypedArray prototypes

  √ Some Array statics (e.g. Uint32Array.from(), Uint32Array.of() ) added to the TypedArray constructors

**Object**

  √ __proto__ in object literal definition sets [[Prototype]] link

  √ Static functions added to Object (Object.getOwnPropertySymbols(), Object.assign() )

  √ Object Literal Computed Property

  √ Object Literal Property Shorthands

  √ Proxies

  √ Reflect

Generator and Promise

  √ Generator function

  √ Promises

Class

  √ Class

  √ super allowed in object methods

  √ class ABC extends Array { .. }

Module

  × Module export command

  × Module import command
  
=========================================

Passes 39 feature Detections

Your runtime supports 92% of ECMAScript 6

=========================================

从上面可以看出,当前版本的Node.js实际上已经支持了大量的ES6特性和语法,但没有支持包的import export。这类问题可以使用Babel解决,将ES6转换为ES5,这样Node.js就支持了所有的ES6特性了。