我创建了一个包含一些库函数的自定义 .scpt
文件,并希望在我的其他脚本中加载该库。
我关注了the official guide由 Apple 提供,这是我得到的:
A) 使用 AppleScript 进行测试
库文件:~/Library/Script Libraries/Sample Library 1.scpt
on changeCase(theText)
set theComparisonCharacters to "abcdefghijklmnopqrstuvwxyz"
set theSourceCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set theAlteredText to ""
repeat with aCharacter in theText
set theOffset to offset of aCharacter in theComparisonCharacters
if theOffset is not 0 then
set theAlteredText to (theAlteredText & character theOffset of theSourceCharacters) as string
else
set theAlteredText to (theAlteredText & aCharacter) as string
end if
end repeat
return theAlteredText
end changeCase
测试脚本
tell script "Sample Library 1"
changeCase("Hello World")
end tell
结果:此解决方案有效。但我想使用 JXA,所以我创建了下面的第二个测试用例。
B) 使用 JXA 进行测试
库文件:~/Library/Script Libraries/Sample Library 2.scpt
function changeCase(text) {
return text.toUpperCase();
}
测试脚本
var lib = Library("Sample Library 2")
lib.changeCase("Hello World")
👉 结果:当我运行脚本时,脚本编辑器崩溃。错误报告中显示以下错误
Application Specific Information:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSXMLDocument initWithData:options:error:]: nil argument'
abort() called
terminating with uncaught exception of type NSException
这里发生了什么,如何修复使用 JXA 时的崩溃?
最佳答案
我找到了解决方案:
库文件~/Library/Script Libraries/Sample Library 2.scpt
需要是一个扩展名为.scptd
的“脚本包”
摘要:
- JXA 库需要保存为“Script-Bundles”(“另存为... → Script-Bundle”)。
- JXA 库只能由其他 JXA 脚本使用
- AppleScript 文件永远无法加载 JXA 库。
- “Script”类型的 AppleScript 库可供其他 AppleScript 文件使用。
- JXA 脚本和 AppleScript 文件可以使用属于“Script-Bundles”的 AppleScript 库。
为了简单起见,我建议将所有库保存为“脚本包”
关于javascript-automation - 在 JXA (AppleScript JS) 中加载脚本库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69887840/