为什么我无法使用PhantomJS 2.1.1渲染我的ReactJS应用程序?

时间:2016-07-19 21:41:56

标签: javascript reactjs phantomjs

为了使用webdriver.io测试我的反应应用程序,我需要使用phantomjs启动它。

起初我认为问题是webdriver.io,但我意识到当我尝试渲染时,PhantomJS会返回一个空白页。

为了进行一些测试,我写了这个javascript文件:

var page = require('webpage').create();
var args = require('system').args;

var output_file = 'example.png', url = args[1];
t = Date.now();

var width = 1440;
var height = 900;
page.viewportSize = { width: width, height: height };
page.paperSize = {
   format: 'A4',
   orientation: 'landscape',
   margin: { left: '1cm', right: '1cm', top: '1cm', bottom: '1cm' }
};

console.log(url);

page.onConsoleMessage = function(msg, lineNum, sourceId) {
  console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};

page.onLoadFinished = function (status) {
    window.setTimeout(function () {
        try {
            page.evaluate(function (w, h) {
                document.body.style.width = w + 'px';
                document.body.style.height = h + 'px';
              }, width, height);
            t = Date.now() - t;
            console.log('Loading ' + url);
            console.log('Loading time ' + t + ' msec');
            page.clipRect = {top: 0, left: 0, width: width, height: height};
            page.render(output_file);
        }
        catch (e) {
            status = e.message;
        }
        console.log(status + ';;' + output_file);
        phantom.exit();
    }, 10000);
};

try {
    page.open(url);
    console.log('loading');
}
catch (ex) {
    console.log(ex.message);
    phantom.exit();
}

我这样推出:phantomjs test.js http://localhost:8080

但无论我做什么,example.png总是空的。

我目前使用React 0.14.7和phantomjs 2.1.1。有没有人知道为什么我无法渲染我的应用程序?

PS:我没有提到,但我对chrome或firefox没有任何问题

2 个答案:

答案 0 :(得分:8)

可能与PhantomJS中缺乏ES6支持有关。要检查我添加了page.onError()回调到您的脚本(总是很方便!)并打开一些React示例站点以获取此错误:

ReferenceError: Can't find variable: Symbol

要填充符号,可以在加载目标网址之前将inject core.js脚本从此优秀的package添加到页面中:

page.onInitialized = function() {
    if(page.injectJs('core.js')){
        console.log("Polyfills loaded");
    }    
}

但那是打开外部网站的。如果正在测试的网站正在开发中(如localhost网址所示),您可能只需配置babel,如this answer所示。

答案 1 :(得分:3)

您可以在https://bitbucket.org/ariya/phantomjs/downloads下载PhantomJS 2.5.0 Beta。

它具有更新的QtWebKit引擎,本机支持ES6。