How to import modules in Swift's JavaScriptCore?

前端 未结 3 797
一生所求
一生所求 2021-02-05 18:16

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\

3条回答
  •  失恋的感觉
    2021-02-05 19:18

    After much bumbling around in the dark, I found a way to make the library available to Swift without having to manually alter it.

    First, as @estus suggested, I installed the library using NPM, which converts it to ES5 but does not resolve the dependencies. So it's still a bunch of separate files that call each other with require and export keywords that neither browsers nor JavaScriptCore understand.

    Then I used Browserify to bundle all the dependencies into a single file so that JavaScriptCore could understand it. The normal operation of Browserify hides all the code, so I used the "--standalone" flag to tell it to make marked functions available. If you export the ES5 file directly, it creates a generic object and puts your exported functions under .default. I want them slightly more accessible, so I created a new file to list the exports and then ran Browserify on that. So for example, a file called "morse-export.js" containing:

    module.exports.MorseMessage = require('./lib/morse-pro-message.js').default;
    

    Then I run Browserify on it like this:

    browserify ./morse-export.js --standalone Morse > ./morse-bundle.js
    

    And include the morse-bundle.js file in my Swift code using Bundle.main.path(forResource). Now I can access the MorseMessage class using Morse.MorseMessage, so back in Swift:

    jsContext?.evaluateScript("var morseMessage = new Morse.MorseMessage()")
    print(jsContext!.evaluateScript("morseMessage.translate('abc')"))
    

    prints ".- -... -.-." as you would expect.

    The downside of this is that you have to manually add whatever classes and functions you want exported to your export file. Still, this seems to be the simplest way to do it. If there's a better way, I would love to hear about it!

提交回复
热议问题