How do I use an NPM javascript package inside of a SwiftUI program? I'm trying to use functions from a package with only one javascript file inside of it for data in an app I am trying to make in SwiftUI. I know that I can use JavaScriptCore to run JavaScript code, but how can I refer to these functions inside of my project. Currently I have an empty project, and I want to use this package to display basic data on a SwiftUI View. If it helps, the package is linked here: [https://github.com/DavidAngell/Aspen-SIS#readme)
How do I use an NPM javascript package inside of a SwiftUI program?
There’s two parts to this:
-
Running JavaScript in JavaScriptCore
-
Running your specific JavaScript
With regards the first part, the basic idea is that you create a VM (JSVirtualMachine) and from there create a context (JSContext). You can then call evaluateScript(_:) to run code in that context. Give this a whirl (with a super simple JavaScript, like 40 + 2) and let me know if you get stuck.
With regards running your specific JavaScript, that very much depends on what it depends on. A lot of JavaScript assumes that it’s running in a browser, and a JavaScriptCore VM does not support all the things that a browser supports. If you find that your JavaScript needs stuff that’s not available in JavaScriptCore, you can either tweak your JavaScript to remove that dependency or add support to JavaScriptCore using either JavaScript, or bridging to native, or some combination of the two.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
- Create a JS project using
npm init - Add your lib in package.json
- Use browserify or any other similar library to generate a "one file JS script" from your npm project
- Load this script using the evaluateScript method
- You will need to write the bridge code to translate/adapt JS objects in to Swift objects and vice-versa