使用 Babel,我如何*不*编译掉 class 属性,因为浏览器现在原生支持它们?
With Babel, how do I *not* compile away class properties, since browsers support them natively now?
鉴于此代码:
class A {
#a = 'hi';
get #b() {
return 'hello' + this.#a;
}
get c() { return this.#b; }
}
我可以运行这个:
let a = new A()
console.log(a.c);
并获得hellohi
Chrome 94 和 Firefox 93+
(只需在开发工具打开时将其输入到控制台即可)。
但是,
在 babel REPL 中,我无法得到相同的结果。
我的浏览器列表是last 1 firefox versions
Example Babel REPL with the env preset - 输出长了 31 行,而根本不应该改变。
此外,还有一些有趣的事情:
- Without the preset:env
- and then with the decorator line uncommented
这里的输出突然应用了 all 转换,尽管根据我的浏览器列表设置,只有 属性 应该对其进行转换(带有装饰器的那个)。在此示例中,似乎 class 属性转换仅支持“全有或全无”?我想这会对构建时间产生巨大的负面影响。
我的问题是:我如何说服 babel 单独保留属性和方法并且不转换它们?
根据caniuse.com:
- 目前 Firefox 和 Chrome 都支持(在撰写本文时分别为 93 和 94):
一般来说,浏览器列表的问题是由于您没有获得您期望的浏览器版本。建议定期更新项目中的 caniuse 数据库,以获取最新版本的 preset-env 浏览器。
你可以这样做:
yarn add -D browserslist@latest
yarn browserslist --update-db
鉴于此代码:
class A {
#a = 'hi';
get #b() {
return 'hello' + this.#a;
}
get c() { return this.#b; }
}
我可以运行这个:
let a = new A()
console.log(a.c);
并获得hellohi
Chrome 94 和 Firefox 93+
(只需在开发工具打开时将其输入到控制台即可)。
但是,
在 babel REPL 中,我无法得到相同的结果。
我的浏览器列表是last 1 firefox versions
Example Babel REPL with the env preset - 输出长了 31 行,而根本不应该改变。
此外,还有一些有趣的事情:
- Without the preset:env
- and then with the decorator line uncommented 这里的输出突然应用了 all 转换,尽管根据我的浏览器列表设置,只有 属性 应该对其进行转换(带有装饰器的那个)。在此示例中,似乎 class 属性转换仅支持“全有或全无”?我想这会对构建时间产生巨大的负面影响。
我的问题是:我如何说服 babel 单独保留属性和方法并且不转换它们?
根据caniuse.com:
- 目前 Firefox 和 Chrome 都支持(在撰写本文时分别为 93 和 94):
一般来说,浏览器列表的问题是由于您没有获得您期望的浏览器版本。建议定期更新项目中的 caniuse 数据库,以获取最新版本的 preset-env 浏览器。
你可以这样做:
yarn add -D browserslist@latest
yarn browserslist --update-db