Skip to content

Instantly share code, notes, and snippets.

@scmx
Last active June 2, 2022 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scmx/1d6c52b73c800afd8dccb62795007633 to your computer and use it in GitHub Desktop.
Save scmx/1d6c52b73c800afd8dccb62795007633 to your computer and use it in GitHub Desktop.
How to write AppleScript JXA JavaScript in Vim or VS Code with TypeScript types #applescript #jxa #javascript #typescript #types #vim #coc

How to write AppleScript JXA JavaScript in Vim or VS Code with TypeScript types

jxa-ts-applescript-typescript

If you have written an AppleScript before, you might have felt the same way as I did, that it was a poor experience to use the Script Editor app, it's barely better than writing the script in any text editor or in a heredoc to run using osascript.

Luckily you could try the JXA variant instead, AppleScript using Javascript. But writing such a file in the Script Editor app is not a better experience sadly.

So I got thinking that there's probably some TypeScript types that could be used. And there is! https://github.com/JXA-userland/JXA

Which means you could get a nice typed experience in VS Code, or even Vim if you have a tsserver language server like coc-tsserver.

Here's an example script

#!/usr/bin/env osascript -l JavaScript
const app = Application.currentApplication();
app.includeStandardAdditions = true;
app.displayDialog("hello");

Here's what I did in the recording:

mkdir jxa
cd jxa
yarn init -y
yarn add -D typescript @jxa/global-type
yarn tsc --init
mv tsconfig.json jsconfig.json
cat <<EOF > script.js
#!/usr/bin/env osascript -l JavaScript
const app = Application.currentApplication();
app.includeStandardAdditions = true;
app.displayDialog("hello");
EOF
chmod u+x script.js
./script.js
  1. Create a script folder with package.json and jsconfig.json with @jxa/global-type types
  2. Make a script.js file that is executable and has a shebang with osascript -l JavaScript
  3. Run it, edit it, run it

To compile it you can run osacompile -l JavaScript -o ~/Applications/Thing.app script.js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment