@babel/plugin-transform-computed-properties
Traduzione Beta Non Ufficiale
Questa pagina è stata tradotta da PageTurner AI (beta). Non ufficialmente approvata dal progetto. Hai trovato un errore? Segnala problema →
informazioni
Questo plugin è incluso in @babel/preset-env
Esempio
In
JavaScript
var obj = {
["x" + foo]: "heh",
["y" + bar]: "noo",
foo: "foo",
bar: "bar",
};
Out
JavaScript
var _obj;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
var obj = ((_obj = {}),
_defineProperty(_obj, "x" + foo, "heh"),
_defineProperty(_obj, "y" + bar, "noo"),
_defineProperty(_obj, "foo", "foo"),
_defineProperty(_obj, "bar", "bar"),
_obj);
Installazione
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-computed-properties
yarn add --dev @babel/plugin-transform-computed-properties
pnpm add --save-dev @babel/plugin-transform-computed-properties
bun add --dev @babel/plugin-transform-computed-properties
Utilizzo
Con un file di configurazione (Consigliato)
Senza opzioni:
babel.config.json
{
"plugins": ["@babel/plugin-transform-computed-properties"]
}
Con opzioni:
babel.config.json
{
"plugins": [
[
"@babel/plugin-transform-computed-properties",
{
"loose": true
}
]
]
}
Tramite CLI
Shell
babel --plugins @babel/plugin-transform-computed-properties script.js
Tramite Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-computed-properties"],
});
Opzioni
loose
boolean, predefinito false
Proprio come l'assegnazione di metodi nelle classi, in modalità loose i nomi delle proprietà calcolate utilizzano semplici assegnazioni invece di essere definiti. È improbabile che questo causi problemi nel codice di produzione.
attenzione
Considera di migrare all'assunzione di primo livello setComputedProperties.
babel.config.json
{
"assumptions": {
"setComputedProperties": true
}
}
Esempio
In
JavaScript
var obj = {
["x" + foo]: "heh",
["y" + bar]: "noo",
foo: "foo",
bar: "bar",
};
Out
Quando setComputedProperties è true.
JavaScript
var _obj;
var obj = ((_obj = {}),
(_obj["x" + foo] = "heh"),
(_obj["y" + bar] = "noo"),
(_obj.foo = "foo"),
(_obj.bar = "bar"),
_obj);
Quando setComputedProperties è false.
JavaScript
import _defineProperty from "@babel/runtime/helpers/defineProperty";
var _obj;
var obj = ((_obj = {}),
_defineProperty(_obj, "x" + foo, "heh"),
_defineProperty(_obj, "y" + bar, "noo"),
_defineProperty(_obj, "foo", "foo"),
_defineProperty(_obj, "bar", "bar"),
_obj);
consiglio
Maggiori informazioni sulla configurazione delle opzioni del plugin sono disponibili qui