Search code examples
iosswifttypescriptwkwebviewjscontext

Is it possible to run TypeScript code in iOS JSContext or WKWebView?


I'm looking for ways to include shared cross platform libraries in native iOS applications. My focus is on Javascript and Typescript sources.

I made a playground project which is loading a js file into JSContext (JavaScriptCore framework) and then I can call JavaSript functions from native Swift code:

let jsContext = JSContext()
let jsURL = Bundle.main.url(forResource: "shared-lib", withExtension: "js")!
let jsScript = try String(contentsOf: jsURL, encoding: .utf8)
jsContext.evaluateScript(jsScript)

jsContext.setObject(
    param1,
    forKeyedSubscript: NSString(string: "param1")
)

jsContext.setObject(
    param2,
    forKeyedSubscript: NSString(string: "param2")
)

let resultJSValue = jsContext.evaluateScript("""
    calculate(param1, param2);
""")

I could also execute js code in WKWebView (WebKit framework), and get the result out of it.

But as soon as I'm trying to execute a simple function from a TypeScript file the result is undefined in both JSContext and WKWebView.

Is it possible at all to run TypeScript code in JSContext or WKWebView?


Solution

  • TypeScript needs to be compiled into JavaScript. Browsers don't support TypeScript directly. So no, you cannot run TypeScript in a JSContext or WKWebView directly.