Given an Node.js module that does not rely on any Node.js functionality except modules
(export/require) how do I access its functions from Objective-C or Swift using JS core?
Example "module":
var compute = function compute(number) {
return 2 * number
};
exports.compute = compute;
Browserified bundle (bundle.js):
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var compute = function compute(number) {
return 2 * number
};
exports.compute = compute;
},{}]},{},[1])
Swift Code:
The code bellow seems not to be able to find the compute
function within the bundle.js
– the result
is NaN
.
var path = b.pathForResource("bundle", ofType: "js")
var source : String = NSString.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)
var context = JSContext()
context.evaluateScript(source)
let compute = context.objectForKeyedSubscript("compute")
let value = compute.callWithArguments([42])
var result = value.toNumber()
How to access "browserified" JavaScript functions?