Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Browserify & iOS JavaScriptCore

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?

like image 324
Zdenek Avatar asked Jun 29 '14 14:06

Zdenek


People also ask

How do I use Browserify require?

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!

What are some of the benefits of Browserify?

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.

What is Browserify in NPM?

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.


1 Answers

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

like image 151
Mike Avatar answered Oct 19 '22 10:10

Mike