简体   繁体   English

如何使用Browserify和iOS JavaScriptCore

[英]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? 给定一个Node.js模块,它不依赖于除modules (export / require)之外的任何Node.js功能,如何使用JS核心从Objective-C或Swift访问其功能?

Example "module": 示例“模块”:

var compute = function compute(number) {
  return 2 * number
};

exports.compute = compute;

Browserified bundle (bundle.js): 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: SWIFT代码:

The code bellow seems not to be able to find the compute function within the bundle.js – the result is NaN . 下面的代码似乎无法在bundle.js找到compute函数 - resultNaN

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? 如何访问“浏览器化”JavaScript函数?

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. thejh的回答一个相关的问题在这里解释说,在默认情况下,browserify不会让你从browserified代码的外部访问的功能和模块。 His answer shows how you could define wrapper functions at the 'window' level which you can then call from ObjC / Swift 他的回答显示了如何在'窗口'级别定义包装函数,然后可以从ObjC / Swift调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM