iOS CommonJS module returns "undefined is not a constructor" error
I'm trying to create an iOS Titanium Module using a pre-compiled CommonJS module. As the README file says:
All JavaScript files in the assets directory are IGNORED except if you create a file named "com.moduletest.js" in this directory in which case it will be wrapped by native code, compiled, and used as your module. This allows you to run pure JavaScript modules that are pre-compiled.
I've created the file like this:
function ModuleTest(url){
if(url){
return url;
}
}
exports.ModuleTest = ModuleTest;
I'm using the 5.1.2.GA SDK (also tried with 5.3.0.GA) and I can build the module successfully either with python build.py
or titanium build --platform iOS --build-only
. Then, in my test app doing:
var test = require('com.moduletest');
var url = new test.ModuleTest('http://url');
Gives me this error:
undefined is not a constructor. I've been trying a lot of alternatives but nothing seems to work and I didn't find any help on documentation about pre-compiled JS modules for iOS. Actually, the same process works great for Android! Do you have some idea why?
My environment:
XCode 7.3.1
Operating System Name - Mac OS X Version - 10.11.5 Architecture - 64bit # CPUs - 8 Memory - 16.0GB
Node.js Node.js Version - 0.12.7 npm Version - 2.11.3
Appcelerator CLI Installer - 4.2.6 Core Package - 5.3.0
Titanium CLI CLI Version - 5.0.9 node-appc Version - 0.2.31
Maybe this is something related to my Node version or appc CLI, not sure =/
Thank you!
There are 2 solutions.
1) Don't put it in assets, but in the /app/lib
folder as others have mentioned.
2) wrap it as an actual commonjs module, like the module I wrote
In both cases, you can just use require('modulename')
. In case 2 you will need to add it to the tiapp.xml
file just like any other module.
The path of your file will come in /modules/commonjs/modulename/version/module.js
or something similar. My linked module will show you the requirements and paths needed.
I use a slightly different pattern that works excellent:
First a small snippet from my "module":
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;
And then this is the way I use it:
var StopWatch = require('utils/StopWatch');
var stopWatch = new StopWatch(listenerFunction);
console.log('elapsed: ' + stopWatch.getElapsed());
链接地址: http://www.djcxy.com/p/96614.html
上一篇: CommonJS / RequireJS