I\'m trying to use Swift\'s JavaScriptCore framework to take advantage of an existing JavaScript library that uses ES6 modules. Specifically, morse-pro by Stephen C Phillips. I\
I too have same issue in accessing my own JS code, which uses 3 external libraries(Lodash, Moment and Moment-range).
Initially i have tried by importing all 4 .js files(1-My own file and 3-libraries) inside my app bundle. But when im trying like this its not worked. I faced issue in place where i have imported those libraries inside my own JS code.
Workaround:
At last i have copied and pasted all codes from those libraries codes inside my own code and imported only one .js file(my own file) inside my app. So in this case no need to import anything from any library. So my code worked successfully.
NOTE: I am not sure whether my workaround is good approach or not. I just thought to register my issue and workaround which helped me.
My code:
lazy var context: JSContext? = {
let context = JSContext()
guard let timeSlotJS = Bundle.main.path(forResource: "app", ofType: "js") else {
print("Unable to read resource file")
return nil
}
do {
let timeSlotContent = try String(contentsOfFile: timeSlotJS, encoding: String.Encoding.utf8)
_ = context?.evaluateScript(timeSlotContent)
} catch {
print("Error on extracting js content")
}
let _ = context?.evaluateScript("var console = { log: function(message) { _consoleLog(message) } }")
// Print log messages
let consoleLog: @convention(block) (String) -> Void = { message in
print("Javascript log: " + message)
}
context?.setObject(unsafeBitCast(consoleLog, to: AnyObject.self), forKeyedSubscript: "_consoleLog" as NSCopying & NSObjectProtocol)
// Print exception messages
context!.exceptionHandler = { context, exception in
print("JS Error: \(exception!)")
}
return context
}()
func accessingJSCode() {
let timeSlotScript = "DigitalVaultTimeSlotAvailabilityFuntion({\"services\": \(services)}, {\"response\": {\"result\": {\"CustomModule1\": {\"row\":\(rowValue)}}, \"uri\": \"/crm/private/json/CustomModule1/searchRecords\"}});"
print(timeSlotScript)
let timeSlots = context!.evaluateScript(timeSlotScript)
// Then here i parsed my output JSON from script.
}
Thanks!!