发布于 1年前

BabelJS - 将 ES8 功能转换为 ES5

BabelJS - 将 ES8 功能转换为 ES5

<figure class="image"></figure>字符串填充是添加到 javascript 中的新 ES8 功能。我们将研究一个简单的示例,它将使用 babel 将字符串填充转换为 ES5。

String Padding

字符串填充根据指定的长度从左侧添加另一个字符串。字符串填充的语法如下所示:

<pre data-language-edit="JavaScript" spellcheck="false">```javascript
str.<span class="hljs">padStart</span>(length, string);
str.<span class="hljs">padEnd</span>(length, string);

<pre data-language-edit="JavaScript" spellcheck="false">```javascript <span class="hljs">const</span> str = <span class="hljs">'abc'</span>;

<span class="hljs">console</span>.<span class="hljs">log</span>(str.<span class="hljs">padStart</span>(<span class="hljs">8</span>, <span class="hljs">''</span>)); <span class="hljs">console</span>.<span class="hljs">log</span>(str.<span class="hljs">padEnd</span>(<span class="hljs">8</span>, <span class="hljs">''</span>));

输出:

<pre data-language-edit="Plain text" spellcheck="false">```plaintext
_____abc
abc_____

<pre data-language-edit="Bash" spellcheck="false">```bash npx babel strpad.js --out-file strpad_es5.js

编译后:

<pre data-language-edit="JavaScript" spellcheck="false">```javascript
<span class="hljs">'use strict'</span>;

<span class="hljs">var</span> str = <span class="hljs">'abc'</span>;

<span class="hljs">console</span>.<span class="hljs">log</span>(str.<span class="hljs">padStart</span>(<span class="hljs">8</span>, <span class="hljs">'_'</span>));
<span class="hljs">console</span>.<span class="hljs">log</span>(str.<span class="hljs">padEnd</span>(<span class="hljs">8</span>, <span class="hljs">'_'</span>));

js 必须与 babel-polyfill 一起使用,如下所示:

<pre data-language-edit="HTML" spellcheck="false">```html <span class="hljs"></span> <span class="hljs"><html></span> <span class="hljs"><head></span> <span class="hljs"><title></span>BabelJs Testing<span class="hljs"></title></span> <span class="hljs"></head></span> <span class="hljs"><body></span> <span class="hljs"><script src="node_modules\babel-polyfill\dist\polyfill.min.js" type="text/javascript"></script></span> <span class="hljs"><script type="text/javascript" src="strpad_es5.js"></script></span> <span class="hljs"></body></span> <span class="hljs"></html></span>

输出如下:

<figure class="image"></figure></body></html>

©2020 edoou.com   京ICP备16001874号-3