Import one script from another?

Here’s an example of how you can set-up a library of Javascript functions for use in Scriptable

Add it to a script entry and run it. It will create a new script file in Scriptable. This new file is the library file and is the same as any other file you might create in Scriptable. It is created with a couple of functions in it. The creation of this file is purely for the purposes of the example. You would typically create this library file yourself in Scriptable.

Once created, the contents of the library file are read in and evaluated. This effectively makes the functions accessible to the current script.

The script then finally outputs some examples to the Scriptable console using those functions from the library.

//This constant is the name of your library file
//It will appear as an entry in Scriptable
const libraryName = "test-lib";

//These constants define where to place your library file
const scriptableFilesPath = "/var/mobile/Library/Mobile Documents/iCloud~dk~simonbs~Scriptable/Documents/";
const libraryPath = `${scriptableFilesPath}${libraryName}.js`;


//Set-up a local file manager object instance
let fmLocal = FileManager.local();

//---
//The content in this section writes a library file
//Typically you would create & maintain the library in Scriptable
//We're only doing it here for the sake of example.

//This next constant defines two functions - square and cube
//This is the content that will be written to the file
const libraryContent = "var square = x => x * x;\nvar cube = x => x * x * x;";
//Create the library file with the content we defined above
let result = fmLocal.writeString(libraryPath, libraryContent);
//---

//Read the content of the library file and interpret it for execution
eval(fmLocal.read(libraryPath));

//---
//Again this section is just for the puposes of the example
//It uses the square and cube functions we wrote out to the library

//Output some values to Scrciptable's console using library functions
console.log(square(6));
console.log(cube(6));
console.log(square(cube(6)));

//---

Here’s some screenshots…

Initial script list

Script and output when run

Resulting script list

Content of additional (library) script

Hope that helps.

10 Likes