@babel/polyfill is a package provided by Babel, a popular JavaScript compiler. The polyfill is a way to bring modern JavaScript features and APIs to older browsers that don't support them natively.
Before ES6 (ECMAScript 2015), JavaScript lacked many features that are now considered standard. Polyfills fill these gaps by providing the missing functionality to older browsers.
Sometimes, specific ECMAScript features or syntax might not be fully supported or may behave differently when executed in JavaScriptCore compared to a regular browser environment.
It's good to catch exceptionHandler to find out if there's error with our bundled js file.
Output additional debug information from your JavaScript code to the Swift environment to understand the context or any potential errors:
let context = JSContext()
context?.exceptionHandler = { context, exception in
if let exception {
print("JS Exception:", exception)
}
}
if let js = JsLoader.load(name: "bundle") {
context?.evaluateScript(js)
}
Call Javascript from Swift
For example this src/index.js file where we use math.js
import * as Math from 'mathjs'
export function evaluate(input) {
return Math.evaluate(input)
}
We can call it from Swift like
let evaluate = context?
.objectForKeyedSubscript("bundle")?
.objectForKeyedSubscript("evaluate")
evaluate.call(withArguments: ["1+2"])
We can use any bundler, like Parcel, Webpack or Vite. Here I use Webpack 5
Install Webpack and Babel
@babel/polyfill
is a package provided by Babel, a popular JavaScript compiler. The polyfill is a way to bring modern JavaScript features and APIs to older browsers that don't support them natively.Before ES6 (ECMAScript 2015), JavaScript lacked many features that are now considered standard. Polyfills fill these gaps by providing the missing functionality to older browsers.
Sometimes, specific ECMAScript features or syntax might not be fully supported or may behave differently when executed in JavaScriptCore compared to a regular browser environment.
Then configure our webpack like this.
webpack.config.js
Setup our JSContext
It's good to catch
exceptionHandler
to find out if there's error with our bundled js file.Output additional debug information from your JavaScript code to the Swift environment to understand the context or any potential errors:
Call Javascript from Swift
For example this
src/index.js
file where we usemath.js
We can call it from Swift like