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?
var compute = function compute(number) {
return 2 * number
};
exports.compute = compute;
(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])
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?
Bundle up your first module With Browserify you can write code that uses require in the same way that you would use it in Node. Browserify parses the AST for require() calls to traverse the entire dependency graph of your project. Drop a single <script> tag into your html and you're done!
Browserify provides a common way to structure all of your JavaScript code by bundling dependencies into a single file that can be referenced within a <script> tag in the browser.
Browserify is an open-source JavaScript bundler tool that allows developers to write and use Node. js-style modules that compile for use in the browser.
thejh's answer to a related question here explains that by default, browserify doesn't let you access the functions and modules from outside of the browserified code. His answer shows how you could define wrapper functions at the 'window' level which you can then call from ObjC / Swift
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With