@babel/plugin-transform-numeric-separator
情報
このプラグインは、ES2021 の @babel/preset-env
に含まれています
例
10進数リテラル
JavaScript
let budget = 1_000_000_000_000;
// What is the value of `budget`? It's 1 trillion!
//
// Let's confirm:
console.log(budget === 10 ** 12); // true
2進数リテラル
JavaScript
let nibbles = 0b1010_0001_1000_0101;
// Is bit 7 on? It sure is!
// 0b1010_0001_1000_0101
// ^
//
// We can double check:
console.log(!!(nibbles & (1 << 7))); // true
16進数リテラル
JavaScript
// Messages are sent as 24 bit values, but should be
// treated as 3 distinct bytes:
let message = 0xa0_b0_c0;
// What's the value of the upper most byte? It's A0, or 160.
// We can confirm that:
let a = (message >> 16) & 0xff;
console.log(a.toString(16), a); // a0, 160
// What's the value of the middle byte? It's B0, or 176.
// Let's just make sure...
let b = (message >> 8) & 0xff;
console.log(b.toString(16), b); // b0, 176
// What's the value of the lower most byte? It's C0, or 192.
// Again, let's prove that:
let c = message & 0xff;
console.log(c.toString(16), b); // c0, 192
8進数リテラル
手を振る絵文字
8進数はパーミッションに最適ですが、0o0000
形式で表現した方が見栄えも良くなります。ここでは区切り文字のメリットはありません。
インストール
- npm
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-numeric-separator
yarn add --dev @babel/plugin-transform-numeric-separator
pnpm add --save-dev @babel/plugin-transform-numeric-separator
使い方
設定ファイルを使う(推奨)
babel.config.json
{
"plugins": ["@babel/plugin-transform-numeric-separator"]
}
CLI経由
Shell
babel --plugins @babel/plugin-transform-numeric-separator script.js
Node API経由
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-numeric-separator"],
});
追加情報
ES2015の10進数、2進数、16進数、8進数の数値表現を、ES2015以前の数値リテラル形式にさらにコンパイルする必要がある場合は、"@babel/plugin-transform-literals"
プラグインを追加してください
情報
@babel/plugin-transform-literals
は、@babel/preset-env にすでに含まれています。
設定ファイルを使う(推奨)
babel.config.json
{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-transform-numeric-separator"]
}
{
"plugins": ["@babel/plugin-transform-numeric-separator", "@babel/plugin-transform-literals"]
}