【问题标题】:iOS CommonJS module returns "undefined is not a constructor" erroriOS CommonJS 模块返回“未定义不是构造函数”错误
【发布时间】:2016-06-29 13:30:39
【问题描述】:

我正在尝试使用预编译的 CommonJS 模块创建 iOS Titanium 模块。正如自述文件所说:

资产目录中的所有 JavaScript 文件都将被忽略,除非您创建一个 此目录中名为“com.moduletest.js”的文件,在这种情况下,它将是 由本机代码包装,编译并用作您的模块。这使您可以 运行预编译的纯 JavaScript 模块。

我创建了这样的文件:

function ModuleTest(url){
 if(url){
   return url;
 }
}
exports.ModuleTest = ModuleTest;

我正在使用 5.1.2.GA SDK(也尝试使用 5.3.0.GA),我可以使用 python build.pytitanium build --platform iOS --build-only 成功构建模块。 然后,在我的测试应用中做:

var test = require('com.moduletest');
var url = new test.ModuleTest('http://url');

给我这个错误:

undefined 不是构造函数。 我一直在尝试很多替代方法,但似乎没有任何效果,而且我没有找到有关 iOS 预编译 JS 模块的文档的任何帮助。实际上,同样的过程也适用于 Android! 你知道为什么吗?

我的环境:

XCode 7.3.1

操作系统 名称 - Mac OS X 版本 - 10.11.5 架构 - 64 位 # CPU - 8 内存 - 16.0GB

Node.js Node.js 版本 - 0.12.7 npm 版本 - 2.11.3

Appcelerator CLI 安装程序 - 4.2.6 核心包 - 5.3.0

钛 CLI CLI 版本 - 5.0.9 节点应用程序版本 - 0.2.31

也许这与我的 Node 版本或 appc CLI 有关,不确定 =/

谢谢!

【问题讨论】:

  • 你把你的文件com.moduletest.js放在哪里了?
  • 嗨 Brenton,我把它放在资产文件夹 moduleTest/assets/com.moduletest.js i.imgur.com/4OW2i86.png
  • 对于 commonjs 模块,您可以直接将它们放在您的应用项目中。尝试将该文件放在您的应用程序的 `/app/lib/com.moduletest.js' 中。
  • @RenePot 下面的解决方案应该可以帮助您。

标签: ios module titanium appcelerator commonjs


【解决方案1】:

有两种解决方案。

1)不要把它放在资产中,而是像其他人提到的那样放在/app/lib文件夹中。

2) 将其包装为实际的 commonjs 模块,例如 module I wrote

在这两种情况下,您都可以使用require('modulename')。在情况 2 中,您需要将其添加到 tiapp.xml 文件中,就像任何其他模块一样。

您的文件路径将采用/modules/commonjs/modulename/version/module.js 或类似名称。我的链接模块将向您展示所需的要求和路径。

【讨论】:

    【解决方案2】:

    我使用了一个稍微不同的模式,效果很好:

    首先是我的“模块”中的一个小sn-p:

    Stopwatch = function(listener) {
        this.totalElapsed = 0; // * elapsed number of ms in total
        this.listener = (listener != undefined ? listener : null); // * function to receive onTick events
    };
    
    Stopwatch.prototype.getElapsed = function() {
        return this.totalElapsed;
    };
    
    module.exports = Stopwatch;
    

    然后这就是我使用它的方式:

    var StopWatch = require('utils/StopWatch');
    var stopWatch = new StopWatch(listenerFunction);
    console.log('elapsed: ' + stopWatch.getElapsed());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 2021-12-31
      相关资源
      最近更新 更多