我在同一目录中有两个文件:
<html>
<head>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js"></script>
<script type="text/javascript">
require(["fakeTest"], function () {});
</script>
</head>
<body>
</body>
</html>
和
define(["require", "exports"], function (require, exports) {
alert('foo');
});
如果我在 Chrome/FireFox 中运行它,我会得到我所期望的结果。如果我尝试使用以下命令从 CMD 运行:
phantomjs --remote-debugger-port=9000 testFile.html
我收到错误:
Error: Cannot find module 'fakeTest'
phantomjs://bootstrap.js:299 in require
phantomjs://bootstrap.js:263 in require
我尝试过最新的 PhantomJS 和旧版本,与 RequireJS 相同。我查遍了谷歌并没有找到任何解决方案。我让其他人在他们的计算机上尝试过此操作,他们也遇到了同样的问题。我已经尽可能地简化了文件,但不确定此时还可以尝试什么。
最佳答案
如果您直接运行 PhantomJS,那么您需要创建一个脚本来加载页面。请参阅下面的示例。也就是说,如果您尝试测试您的网页,则有 headless testing frameworks设计用于与 PhantomJS 配合使用。这些框架负责在运行测试时加载 HTML、脚本和其他资源的细节。就我个人而言,我使用Karma Test Runner与 karma-requirejs plugin运行单元测试。
如果您尝试直接运行 PhatomJS,您需要创建一个脚本来打开 HTML 页面。在下面的简单示例 run.js 中,打开“testFile.html”页面,并打印页面的标题。然后它设置 100 毫秒的超时时间,再次打印标题并退出。
var page = require('webpage').create();
page.open('testFile.html', function(status) {
var title = page.evaluate(function() {
return document.title;
});
console.log('Page title is ' + title);
setTimeout(function () {
var title = page.evaluate(function () {
return document.title;
});
console.log('Page title is ' + title);
phantom.exit()
}, 100);
});
下面是运行命令的输出示例:
phantomjs run.js
Page title is Original Title
Page title is Title Updated
超时的原因是 AMD 模块是异步加载的,您需要在 run.js 脚本中构建一种方法来考虑 AMD 模块的异步性质。我强烈建议使用与 RequireJS 集成的现有测试运行器之一,而不是重新发明轮子。
要查看实际效果,请将 testFile.html 修改为:
<html>
<head>
<title>Original Title</title>
<script type="text/javascript"
src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js">
</script>
<script type="text/javascript">
require(["fakeTest"], function () {});
</script>
</head>
<body>
</body>
</html>
fakeTest.js 为:
define(["require", "exports"], function (require, exports) {
document.title = 'Title Updated';
});
关于javascript - PhantomJS 中出现 RequireJS 错误,但 Chrome/FireFox 中没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34887340/