ExtendScript: Importing Libraries

As scripts to automate your workflows become more complex, there becomes a need to break out commonly reused code into functions. This helps to avoid repeating code, leading to a solution that is much easier to maintain.

Functions within ExtendScript work as expected if you are familiar with JavaScript and if we define them in the same file as our main script, we can use them directly. For example:

#target photoshop

standardFunction();

function standardFunction(){
    $.writeln("The standard function was executed!");
    }

This code will print “The standard function was executed!” to the ExtendScript Toolkit console, indicating that the standardFunction() was successfully called.

This is great, but eventually a script may continue to grow until keeping all of the code within a single file becomes bulky and annoying to work with. In this case it makes sense to start breaking out related functions in to separate library files which can be imported by the main script. As JavaScript has evolved, the standard methods for doing this have as well (as discussed here on Stack Overflow). That being said, the methods for doing this within ExtendScript are different still.

There are three ways within ExtendScript to utilize code from external scripts. All of the examples below will be utilizing a file named “library.jsxlib” which is located in the same directory as the primary script and containing the following code:

function libraryFunction(){
  $.writeln("The imported library function was executed!");
}
  1. #include:
    This syntax is straightforward to use. Place this statement near the top of your file and use a string representing the path (relative or absolute) to the library file.

    #target photoshop
    #include "./library.jsxlib"
    libraryFunction();
  2. //@include:
    This syntax is similar to #1, but because it has the two forward slashes, it won’t cause a linter to produce errors like the first one will if you are using one.

    #target photoshop
    //@include "./library.jsxlib"
    libraryFunction();
  3. $.evalFile():

    According to the ESTK documentation, $.evalFile() “Loads and evaluates a file.” The method can take a File object or an absolute path as its input, so rather than using a relative path to the library file, the full path must be built.

    #target photoshop
    var libraryFileName = "library.jsxlib";
    var libraryFilePath = File($.fileName).path + "/" + libraryFileName;
    $.evalFile(libraryFilePath);
    libraryFunction();

Finally, when working with growing scripts using multiple include statements, it is important to consider naming conflicts. If multiple libraries contain functions with the same name, one will overwrite the other leading to runtime errors or subtly incorrect behaviors.

Hopefully these options will help you better organize your code as you begin to expand your automation capabilities!