我正在尝试将PhantomJS与Babel从ES6编译到ES5的脚本一起使用。
对于某些功能,Babel会在文件末尾添加一些帮助函数(如_asyncToGenerator
和_typeof
)来评估代码。
但是在Phantom中,有一个函数evaluate(function(){…})
在浏览器上下文中执行,因此它无法访问babel放入的辅助函数。
例如,如果我有代码:
var page = require('webpage').create();
page.open(url, function(status) {
var title = page.evaluate(function() {
typeof(document.title);
});
});
它编译为
var page = require('webpage').create();
page.open(url, function(status) {
var title = page.evaluate(function Executed_in_Browser_Context() {
_typeof(document.title);
});
});
function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }
请注意,typeof
已更改为_typeof
(针对某些涉及ES6符号的功能)
这里,function Executed_in_Browser_Context
在浏览器上下文中执行,因此它无权访问底部文件中定义的function _typeof
。因此导致错误
Can't find variable: _typeof
如何解决这个问题?
我尝试复制_typeof
里面Executed_in_Browser_Context
(预编译)但是在编译之后,Babel看到并认为它可能是我的代码中的其他函数,只是重命名它自己的_typeof2
导致同样的错误。