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

Gwe*_*erc 9 javascript phantomjs reactjs

为了使用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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Vav*_*off 8

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

ReferenceError: Can't find variable: Symbol

填充符号,可以在加载目标URL之前将此优秀包中core.js脚本注入页面:

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

但这是打开外部网站.如果正在测试的站点正在开发中(如localhost url建议的那样),您可能只需配置babel,如本答案所示.