第1章 ECMAScript 6简介
ECMAScript 6(以下简称ES6)是JavaScript语言的下一代标准,已于2015年6月正式发布。它的目标是使JavaScript语言可以用于编写复杂的大型应用程序,成为企业级开发语言。
1.1 ECMAScript 和 JavaScript 的关系
ECMAScript 和 JavaScript 的关系是,前者是后者的规格,后者是前者的一种实现(另外的 ECMAScript 方言还有 JScript 和 ActionScr)。
1.2 ES6 与 ECMAScript 2015 的关系
ES6 既是一个历史名词,也是一个泛指,含义是5.1版本以后的 JavaScript 的下一代标准,涵盖了ES2015、ES2016、ES2017等,而ES2015则是正式名称,特指当年发布的正式版本的语言标准。
1.3 语法提案的批准流程
一种新的语法从提案到变成正式标准,需要经历五个阶段。每个阶段的变动都要由 TC39 委员会批准。
- Stage 0:Strawman(展示阶段)
- Stage 1:Proposal(征求意见阶段)
- Stage 2:Draft(草案阶段)
- Stage 3:Candidate(候选阶段)
- Stage 4:Finished(定案阶段)
1.4 ECMAScript的历史
【评】没有重点,省略。
1.5 部署进度
关于各大浏览器最新版本对于ES6的支持,可以参阅 kangax.github.io/es5-compat-table/es6/。
随着时间的推移,支持度已经越来越高,超过90%的ES6语法特性都实现了。
Node 是 JavaScript 语言的服务器运行环境(runtime),它对ES6的支持度更高。除了那些默认打开的功能,还有一些语法功能也已经实现了,但是默认没有打开。使用如下命令,可以查看 Node 中已经实现的ES6特性。
node --v8-options | grep harmony
输入这条命令,结果显示的是:
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 C:\Users\Administrator>node --v8-options | grep harmony 'grep' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 C:\Users\Administrator>
所以,我改成输入以下这条命令:
node --v8-options
是可以成功显示的:
type: bool default: false --trace-compiler-dispatcher (trace compiler dispatcher activity) type: bool default: false --cpu-profiler-sampling-interval (CPU profiler sampling interval in microsecon ds) type: int default: 1000 --trace-side-effect-free-debug-evaluate (print debug messages for side-effect- free debug-evaluate for testing) type: bool default: false --hard-abort (abort by crashing) type: bool default: true --expose-inspector-scripts (expose injected-script-source.js for debugging) type: bool default: false --stack-size (default size of stack region v8 is allowed to use (in kBytes)) type: int default: 984 --max-stack-trace-source-length (maximum length of function source code printe d in a stack trace.) type: int default: 300 --clear-exceptions-on-js-entry (clear pending exceptions when entering JavaScr ipt) type: bool default: false --histogram-interval (time interval in ms for aggregating memory histograms) type: int default: 600000 --heap-profiler-trace-objects (Dump heap object allocations/movements/size_upd ates) type: bool default: false --heap-profiler-use-embedder-graph (Use the new EmbedderGraph API to get embed der nodes) type: bool default: true --heap-snapshot-string-limit (truncate strings to this length in the heap snap shot) type: int default: 1024 --sampling-heap-profiler-suppress-randomness (Use constant sample intervals to eliminate test flakiness) type: bool default: false --use-idle-notification (Use idle notification to reduce memory footprint.) type: bool default: true --trace-ic (trace inline cache state transitions for tools/ic-processor) type: bool default: false --modify-field-representation-inplace (enable in-place field representation up dates) type: bool default: true --max-polymorphic-map-count (maximum number of maps to track in POLYMORPHIC st ate) type: int default: 4 --native-code-counters (generate extra code for manipulating stats counters) type: bool default: false --thin-strings (Enable ThinString support) type: bool default: true --trace-prototype-users (Trace updates to prototype user tracking) type: bool default: false --use-verbose-printer (allows verbose printing) type: bool default: true --trace-for-in-enumerate (Trace for-in enumerate slow-paths) type: bool default: false --trace-maps (trace map creation) type: bool default: false --trace-maps-details (also log map details) type: bool default: true --allow-natives-syntax (allow natives syntax) type: bool default: false --parse-only (only parse the sources) type: bool default: false --trace-sim (Trace simulator execution) type: bool default: false --debug-sim (Enable debugging the simulator) type: bool default: false --check-icache (Check icache flushes in ARM and MIPS simulator) type: bool default: false --stop-sim-at (Simulator stop after x number of instructions) type: int default: 0 --sim-stack-alignment (Stack alingment in bytes in simulator (4 or 8, 8 is def ault)) type: int default: 8 --sim-stack-size (Stack size of the ARM64, MIPS64 and PPC64 simulator in kByte s (default is 2 MB)) type: int default: 2048 --log-colour (When logging, try to use coloured output.) type: bool default: false --ignore-asm-unimplemented-break (Don't break for ASM_UNIMPLEMENTED_BREAK macr os.) type: bool default: false --trace-sim-messages (Trace simulator debug messages. Implied by --trace-sim.) type: bool default: false --async-stack-traces (include async stack traces in Error.stack) type: bool default: true --stack-trace-on-illegal (print stack trace when an illegal exception is throw n) type: bool default: false --abort-on-uncaught-exception (abort program (dump core) when an uncaught exce ption is thrown) type: bool default: false --correctness-fuzzer-suppressions (Suppress certain unspecified behaviors to e ase correctness fuzzing: Abort program when the stack overflows or a string exce eds maximum length (as opposed to throwing RangeError). Use a fixed suppression string for error messages.) type: bool default: false --randomize-hashes (randomize hashes to avoid predictable hash collisions (wit h snapshots this option cannot override the baked-in seed)) type: bool default: true --rehash-snapshot (rehash strings from the snapshot to override the baked-in s eed) type: bool default: true --hash-seed (Fixed seed to use to hash property keys (0 means random)(with sna pshots this option cannot override the baked-in seed)) type: uint64 default: 0 --random-seed (Default seed for initializing random generator (0, the default, means to use system random).) type: int default: 0 --fuzzer-random-seed (Default seed for initializing fuzzer random generator (0 , the default, means to use v8's random number generator seed).) type: int default: 0 --trace-rail (trace RAIL mode) type: bool default: false --print-all-exceptions (print exception object and stack trace on each thrown exception) type: bool default: false --detailed-error-stack-trace (includes arguments for each function call in the error stack frames array) type: bool default: false --runtime-call-stats (report runtime call counts and times) type: bool default: false --profile-deserialization (Print the time it takes to deserialize the snapshot .) type: bool default: false --serialization-statistics (Collect statistics on serialized objects.) type: bool default: false --serialization-chunk-size (Custom size for serialization chunks) type: uint default: 4096 --regexp-optimization (generate optimized regexp code) type: bool default: true --regexp-mode-modifiers (enable inline flags in regexp.) type: bool default: false --regexp-interpret-all (interpret all regexp code) type: bool default: false --regexp-tier-up (enable regexp interpreter and tier up to the compiler) type: bool default: false --testing-bool-flag (testing_bool_flag) type: bool default: true --testing-maybe-bool-flag (testing_maybe_bool_flag) type: maybe_bool default: unset --testing-int-flag (testing_int_flag) type: int default: 13 --testing-float-flag (float-flag) type: float default: 2.5 --testing-string-flag (string-flag) type: string default: Hello, world! --testing-prng-seed (Seed used for threading test randomness) type: int default: 42 --testing-d8-test-runner (test runner turns on this flag to enable a check tha t the funciton was prepared for optimization before marking it for optimization) type: bool default: false --embedded-src (Path for the generated embedded data file. (mksnapshot only)) type: string default: nullptr --embedded-variant (Label to disambiguate symbols in embedded data file. (mksn apshot only)) type: string default: nullptr --startup-src (Write V8 startup as C++ src. (mksnapshot only)) type: string default: nullptr --startup-blob (Write V8 startup blob file. (mksnapshot only)) type: string default: nullptr --target-arch (The mksnapshot target arch. (mksnapshot only)) type: string default: nullptr --target-os (The mksnapshot target os. (mksnapshot only)) type: string default: nullptr --minor-mc-parallel-marking (use parallel marking for the young generation) type: bool default: true --trace-minor-mc-parallel-marking (trace parallel marking for the young genera tion) type: bool default: false --minor-mc (perform young generation mark compact GCs) type: bool default: false --help (Print usage message, including flags, on console) type: bool default: true --dump-counters (Dump counters on exit) type: bool default: false --dump-counters-nvp (Dump counters as name-value pairs on exit) type: bool default: false --use-external-strings (Use external strings for source code) type: bool default: false --map-counters (Map counters to a file) type: string default: --mock-arraybuffer-allocator (Use a mock ArrayBuffer allocator for testing.) type: bool default: false --mock-arraybuffer-allocator-limit (Memory limit for mock ArrayBuffer allocato r used to simulate OOM for testing.) type: size_t default: 0 --log (Minimal logging (no API, code, GC, suspect, or handles samples).) type: bool default: false --log-all (Log all events to the log file.) type: bool default: false --log-api (Log API events to the log file.) type: bool default: false --log-code (Log code events to the log file without profiling.) type: bool default: false --log-handles (Log global handle events.) type: bool default: false --log-suspect (Log suspect operations.) type: bool default: false --log-source-code (Log source code.) type: bool default: false --log-function-events (Log function events (parse, compile, execute) separatel y.) type: bool default: false --prof (Log statistical profiling information (implies --log-code).) type: bool default: false --detailed-line-info (Always generate detailed line information for CPU profil ing.) type: bool default: false --prof-sampling-interval (Interval for --prof samples (in microseconds).) type: int default: 1000 --prof-cpp (Like --prof, but ignore generated code.) type: bool default: false --prof-browser-mode (Used with --prof, turns on browser-compatible mode for pr ofiling.) type: bool default: true --logfile (Specify the name of the log file.) type: string default: v8.log --logfile-per-isolate (Separate log files for each isolate.) type: bool default: true --ll-prof (Enable low-level linux profiler.) type: bool default: false --perf-basic-prof (Enable perf linux profiler (basic support).) type: bool default: false --perf-basic-prof-only-functions (Only report function code ranges to perf (i. e. no stubs).) type: bool default: false --perf-prof (Enable perf linux profiler (experimental annotate support).) type: bool default: false --perf-prof-annotate-wasm (Used with --perf-prof, load wasm source map and pro vide annotate support (experimental).) type: bool default: false --perf-prof-unwinding-info (Enable unwinding info for perf linux profiler (exp erimental).) type: bool default: false --gc-fake-mmap (Specify the name of the file for fake gc mmap used in ll_prof) type: string default: /tmp/__v8_gc__ --log-internal-timer-events (Time internal events.) type: bool default: false --log-instruction-stats (Log AArch64 instruction statistics.) type: bool default: false --log-instruction-file (AArch64 instruction statistics log file.) type: string default: arm64_inst.csv --log-instruction-period (AArch64 instruction statistics logging period.) type: int default: 4194304 --redirect-code-traces (output deopt information and disassembly into file cod e-<pid>-<isolate id>.asm) type: bool default: false --redirect-code-traces-to (output deopt information and disassembly into the g iven file) type: string default: nullptr --print-opt-source (print source code of optimized and inlined functions) type: bool default: false --win64-unwinding-info (Enable unwinding info for Windows/x64) type: bool default: true --interpreted-frames-native-stack (Show interpreted frames on the native stack (useful for external profilers).) type: bool default: false --trace-elements-transitions (trace elements transitions) type: bool default: false --trace-creation-allocation-sites (trace the creation of allocation sites) type: bool default: false --print-code (print generated code) type: bool default: false --print-opt-code (print optimized code) type: bool default: false --print-opt-code-filter (filter for printing optimized code) type: string default: * --print-code-verbose (print more information for code) type: bool default: false --print-builtin-code (print generated code for builtins) type: bool default: false --print-builtin-code-filter (filter for printing builtin code) type: string default: * --print-regexp-code (print generated regexp code) type: bool default: false --print-regexp-bytecode (print generated regexp bytecode) type: bool default: false --print-builtin-size (print code size for builtins) type: bool default: false --sodium (print generated code output suitable for use with the Sodium code vi ewer) type: bool default: false --print-all-code (enable all flags related to printing code) type: bool default: false --predictable (enable predictable mode) type: bool default: false --predictable-gc-schedule (Predictable garbage collection schedule. Fixes heap growing, idle, and memory reducing behavior.) type: bool default: false --single-threaded (disable the use of background tasks) type: bool default: false --single-threaded-gc (disable the use of background gc tasks) type: bool default: false C:\Users\Administrator>
执行以上命令,输出结果会因为版本的不同而有所不同。
笔者写了一个ES-Checker( github.com/ruanyf/es-checker )模块,用来检查各种运行环境对ES6的支持情况。
访问 ruanyf.github.io/es-checker 即可查看所用浏览器对ES6的支持程度。
运行下面的命令,可以查看本机对ES6的支持程度。
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 C:\Users\Administrator>npm install -g es-checker F:\Program Files\nodejs\es-checker -> F:\Program Files\nodejs\node_modules\es-ch ecker\bin\check.js + es-checker@1.4.2 added 13 packages from 8 contributors in 10.119s C:\Users\Administrator>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.prot otype.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(), Float6 4Array() √ Some Array methods (e.g. Int8Array.prototype.slice(), Int8Array.prototype.j oin(), Int8Array.prototype.forEach() ) added to the TypedArray prototypes √ Some Array statics (e.g. Uint32Array.from(), Uint32Array.of() ) added to th e TypedArray constructors Object √ __proto__ in object literal definition sets [[Prototype]] link √ Static functions added to Object (Object.getOwnPropertySymbols(), Object.as sign() ) √ 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 =========================================
1.6 Babel转码器
Babel( babeljs.io/ ) 是一个广为使用的ES6转码器,可以将ES6代码转为ES5代码,从而在浏览器或其他环境执行。这意味着,可以用ES6的方式编写程序,而不用担心现有环境是否支持。
下面是一个例子。
上面的原始代码用了箭头函数,Babel 将其转为普通函数,这样就能在不支持箭头函数的 JavaScript 环境中执行了。
1.6.1 配置文件.babelrc
Babel的配置文件是.babelrc,存放在项目的根目录下。
使用 Babel 的第一步就是配置这个文件。
该文件用来设置转码规则和插件,基本格式如下。
{ "presets": [], "plugins": [] }
presets 字段设定转码规则,官方提供以下的规则集,可以根据需要进行安装。
# 最新转码规则 $ npm install --save-dev babel-preset-latest
安装的结果:
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>npm install --save-dev babel-preset-latest npm WARN deprecated babel-preset-latest@6.24.1: We're super 😸 excited that you 're trying to use ES2017+ syntax, but instead of making more yearly presets 😭 , Babel now has a better preset that we recommend you use instead: npm install ba bel-preset-env --save-dev. preset-env without options will compile ES2015+ down to ES5 just like using all the presets together and thus is more future proof. I t also allows you to target specific browsers so that Babel can do less work and you can ship native ES2015+ to user 😎 ! We are also in the process of releasin g v7, so please give http://babeljs.io/blog/2017/09/12/planning-for-7.0 a read a nd help test it out in beta! Thanks so much for using Babel 🙏, please give us a follow on Twitter @babeljs for news on Babel, join slack.babeljs.io for discuss ion/development and help support the project at opencollective.com/babel npm WARN deprecated babel-preset-es2015@6.24.1: 🙌 Thanks for using Babel: we r ecommend using babel-preset-env now: please read https://babeljs.io/env to updat e! npm WARN deprecated babel-preset-es2016@6.24.1: 🙌 Thanks for using Babel: we r ecommend using babel-preset-env now: please read https://babeljs.io/env to updat e! npm WARN deprecated babel-preset-es2017@6.24.1: 🙌 Thanks for using Babel: we r ecommend using babel-preset-env now: please read https://babeljs.io/env to updat e! npm WARN deprecated core-js@2.6.12: core-js@<3.4 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whi ms, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual v ersion of core-js. > core-js@2.6.12 postinstall E:\HMV\node_modules\core-js > node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfill ing JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Colle ctive or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock Also, the author of core-js ( https://github.com/zloirock ) is looking for a goo d job -) npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN HMV No description npm WARN HMV No repository field. npm WARN HMV No license field. + babel-preset-latest@6.24.1 added 78 packages from 14 contributors and removed 19 packages in 18.695s E:\HMV\Babel>
# react 转码规则 $ npm install --save-dev babel-preset-react
安装的结果:
E:\HMV\Babel>npm install --save-dev babel-preset-react npm WARN HMV No description npm WARN HMV No repository field. npm WARN HMV No license field. + babel-preset-react@6.24.1 added 10 packages from 2 contributors and removed 1 package in 5.248s
# 不同阶段语法提案的转码规则(共有4个阶段),选装一个 $ 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
安装的结果:
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>npm install --save-dev babel-preset-stage-2 npm WARN HMV No description npm WARN HMV No repository field. npm WARN HMV No license field. + babel-preset-stage-2@6.24.1 added 13 packages from 1 contributor and removed 1 package in 9.291s E:\HMV\Babel>
然后,将这些规则加入.babelrc中。
{ "presets": [ "latest", "react", "stage-2" ], "plugins": [] }
1.6.2 命令行转码babel-cli
Babel 提供 babel-cli 工具,用于命令行转码。
它的安装命令如下。
$ npm install --global babel-cli
安装结果如下:
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>npm install --global babel-cli npm WARN deprecated chokidar@1.7.0: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies. npm WARN deprecated core-js@2.6.12: core-js@<3.4 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whi ms, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual v ersion of core-js. npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and coul d be using insecure binaries. Upgrade to fsevents 2. npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/sour ce-map-resolve#deprecated npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-m ap-url#deprecated npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprec ated npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#dep recated F:\Program Files\nodejs\babel-node -> F:\Program Files\nodejs\node_modules\babel -cli\bin\babel-node.js F:\Program Files\nodejs\babel-doctor -> F:\Program Files\nodejs\node_modules\bab el-cli\bin\babel-doctor.js F:\Program Files\nodejs\babel -> F:\Program Files\nodejs\node_modules\babel-cli\ bin\babel.js F:\Program Files\nodejs\babel-external-helpers -> F:\Program Files\nodejs\node_m odules\babel-cli\bin\babel-external-helpers.js > core-js@2.6.12 postinstall F:\Program Files\nodejs\node_modules\babel-cli\node _modules\core-js > node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfill ing JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Colle ctive or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock Also, the author of core-js ( https://github.com/zloirock ) is looking for a goo d job -) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\ba bel-cli\node_modules\chokidar\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@ 1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64" }) + babel-cli@6.26.0 added 234 packages from 119 contributors in 61.661s E:\HMV\Babel>
babel-cli 基本用法
基本用法如下。
转码结果输出到标准输出
# 转码结果输出到标准输出 $ babel hzh.js
直接使用源文件名字进行转码:
// hzh.js var input = [1, 2, 3]; input.map(item => item + 1);
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>babel hzh.js "use strict"; var input = [1, 2, 3]; input.map(function (item) { return item + 1; }); E:\HMV\Babel>
转码结果写入一个文件
# 转码结果写入一个文件 # --out-file 或 -o 参数指定输出文件 $ babel hzh.js --out-file huangzihan.js # 或者 $ babel hzh.js --o huangzihan.js
下面是hzh.js和huangzihan.js两个文件的代码:
// hzh.js var input = [1, 2, 3]; input.map(item => item + 1); // huangzihan.js "use strict"; var input = [1, 2, 3]; input.map(function (item) { return item + 1; });
终端的输入和输出是这样的:
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>babel hzh.js -o huangzihan.js E:\HMV\Babel>
整个目录转码
# 整个目录转码 # --out-dir 或 -d 参数指定输出目录 $ babel hzh1 --out-dir hzh2 # 或者 $ babel hzh1 -d hzh2
下面是hzh1目录下hzh11.js和hzh12.js文件的代码:
// hzh11.js var hzh11 = [1, 2, 3]; hzh11.map(item => item + 1); // hzh12.js var hzh12 = [1, 2, 3]; hzh12.map(item => item + 1);
转码之前项目目录的结构:
终端的输入和输出:
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>babel hzh1 -d hzh2 hzh1\hzh11.js -> hzh2\hzh11.js hzh1\hzh12.js -> hzh2\hzh12.js E:\HMV\Babel>
转码之后项目目录的结构:
生成 source map 文件
# -s 参数 生成source map 文件 $ babel hzh1 -d hzh2 -s
转码之前项目目录的结构:
转码之前hzh1目录下各个文件的代码:
// hzh1.js var hzh11 = [1, 2, 3]; hzh11.map(item => item + 1); // hzh2.js var hzh12 = [1, 2, 3]; hzh12.map(item => item + 1);
终端的输入与输出:
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>babel hzh1 -d hzh2 -s hzh1\hzh11.js -> hzh2\hzh11.js hzh1\hzh12.js -> hzh2\hzh12.js E:\HMV\Babel>
转码之后项目目录的结构:
转码之后hzh2目录下各个文件的代码:
// hzh11.js "use strict"; var hzh11 = [1, 2, 3]; hzh11.map(function (item) { return item + 1; }); //# sourceMappingURL=hzh11.js.map // hzh11.js.map {"version":3,"sources":["../hzh1/hzh11.js"],"names":["hzh11","map","item"],"mappings":";;AAAA,IAAIA,QAAQ,CAAC,CAAD,EAAI,CAAJ,EAAO,CAAP,CAAZ;AACAA,MAAMC,GAAN,CAAU;AAAA,SAAQC,OAAO,CAAf;AAAA,CAAV","file":"hzh11.js","sourcesContent":["var hzh11 = [1, 2, 3];\r\nhzh11.map(item => item + 1);"]} // hzh12.js "use strict"; var hzh12 = [1, 2, 3]; hzh12.map(function (item) { return item + 1; }); //# sourceMappingURL=hzh12.js.map // hzh12.js.map {"version":3,"sources":["../hzh1/hzh12.js"],"names":["hzh12","map","item"],"mappings":";;AAAA,IAAIA,QAAQ,CAAC,CAAD,EAAI,CAAJ,EAAO,CAAP,CAAZ;AACAA,MAAMC,GAAN,CAAU;AAAA,SAAQC,OAAO,CAAf;AAAA,CAAV","file":"hzh12.js","sourcesContent":["var hzh12 = [1, 2, 3];\r\nhzh12.map(item => item + 1);"]}
在项目中运行 Babel
上面的代码是在全局环境下进行 Babel 转码的。这意味着,如果项目要运行,全局环境中必须有 Babel,也就是说项目产生了对环境的依赖。另一方面,这样做也无法支持不同项目使用不同版本的Babel。
一个解决办法是将 babel-cli 安装在项目之中,代码如下。
什么项目需要再回来看下这个,先摘抄下来。
# 安装 $ npm install --save-dev babel-cli
然后,改写package.json。
{ // ... "devDependencies": { "babel-cli": "^6.0.0" }, "scripts": { "build": "babel src -d lib" }, }
转码的时候需要执行以下命令。
$ npm run build
1.6.3 babel-node
babel-cli 工具自带一个babel-node命令,提供一个支持 ES6 的 REPL 环境。它支持 Node 的 REPL 环境的所有功能,而且可以直接运行 ES6 代码。
babel-node 不用单独安装,而是随 babel-cli 一起安装。执行 babel-node 可以进入 REPL 环境。
$ babel-node > (x => x * 2)(1) 2
模仿上面的代码,在终端上输入和输出的结果:
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>babel-node > (hzh => hzh * 3)(2) 6 >
babel-node 命令可以直接运行 ES6 脚本。将上面的代码放入脚本文件 es6.js,然后直接运行。
$ babel-node es6.js 2
根据上面的描述,我在项目目录下新建了一个hzh.js文件,一开始直接将上面的套进去发现是没有输出的,经过思考,修改为下面的代码,就有了输出,下面分别给出hzh.js和终端的代码:
// hzh.js console.log((hzh => hzh * 4)(3));
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>babel-node hzh.js 12
babel-node 也可以安装在项目中。
$ npm install --save-dev babel-cli
安装的结果如下:
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。保留所有权利。 E:\HMV\Babel>npm install --save-dev babel-cli npm WARN deprecated chokidar@1.7.0: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies. npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2. npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN HMV No description npm WARN HMV No repository field. npm WARN HMV No license field. + babel-cli@6.26.0 added 211 packages from 122 contributors and removed 1 package in 81.97s 2 packages are looking for funding run `npm fund` for details E:\HMV\Babel>
然后,改写 package.json。
{ "script": { "script-name": "babel-node script.js" } }
在以上代码中,使用 babel-node 替代 node,这样 script.js 本身就不用进行任何转码处理了
这句不太明白是啥意思?
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?