使用 ECMAScript 6

使用 ECMAScript 6

问题描述:

我正在寻找一种在浏览器控制台中运行 ECMAScript 6 代码的方法,但大多数浏览器不支持我正在寻找的功能.例如 Firefox 是唯一支持箭头功能的浏览器.

I'm looking for a way to run ECMAScript 6 code in my browser's console but most browsers don't support functionality that I'm looking for. For example Firefox is the only browser that supports arrow functions.

有没有办法(扩展程序、用户脚本等)可以在 Chrome 上运行这些功能?

Is there a way (extension, userscript, etc.) I can run these features on Chrome?

在 Chrome 中,大多数 ES6 功能都隐藏在一个称为实验性 JavaScript 功能"的标志后面.访问 chrome://flags/#enable-javascript-harmony,启用这个标志,重启 Chrome,你会得到 许多新功能.

In Chrome, most of the ES6 features are hidden behind a flag called "Experimental JavaScript features". Visit chrome://flags/#enable-javascript-harmony, enable this flag, restart Chrome and you will get many new features.

箭头函数尚未在 V8/Chrome 中实现,所以这个标志不会解锁"箭头功能.

Arrow functions are not yet implemented in V8/Chrome, so this flag won't "unlock" arrow functions.

由于箭头函数是一种语法变化,如果不改变 JavaScript 的解析方式,就不可能支持这种语法.如果您喜欢使用 ES6 进行开发,那么您可以编写 ES6 代码并使用 ES6-to-ES5 编译器生成与所有现有(现代)浏览器兼容的 JavaScript 代码.

Since arrow functions are a syntax change, it is not possible to support this syntax without changing the way how JavaScript is parsed. If you love developing in ES6, then you could write ES6 code and use an ES6-to-ES5 compiler to generate JavaScript code that is compatible with all existing (modern) browsers.

例如,请参阅https://github.com/google/traceur-compiler.在撰写本文时,它支持 ES6 的所有新语法特性.连同此答案顶部提到的标志,您将非常接近所需的结果.

For example, see https://github.com/google/traceur-compiler. As of writing, it supports all of the new syntax features of ES6. Together with the flag mentioned at the top of this answer, you will get very close to the desired result.

如果你想直接从控制台运行 ES6 语法,那么你可以尝试覆盖控制台的 JavaScript 评估器(这样在执行代码之前运行 Traceur 预处理器).如果您喜欢这样做,请查看 这个答案 了解如何修改开发者工具的行为.

If you want to run ES6 syntax directly from the console, then you could try to overwrite the JavaScript evaluator of the console (such that Traceur preprocesor is run before executing the code). If you fancy doing this, have a look at this answer to learn how to modify the behavior of the developer tools.