logo
logo

How to create a Shared script using Visual Studio Code

Shared scripts allow to maintain and reuse commonly used code in a separate script that can be referenced by one or more scripts of any type.

Prerequisites

Initialize your working folder

First initialize your working folder with the files needed to support Intellisense in Visual Studio Code. The working folder can be any folder selected by you.

Run command

ch-cli scripting initialize -f <your-folder-path>

Once initialized the working folder should contain the following files:

[working folder]
├── omnisharp.json
├── references.json
├── lib
│   ├── Newtonsoft.Json.dll
│   ├── Remotion.Linq.dll
│   ├── Stylelabs.M.Scripting.Types.dll
│   ├── Stylelabs.M.Sdk.dll
│   ├── Stylelabs.M.Sdk.Fluent.dll
│   ├── Stylelabs.M.Sdk.ScriptClient.dll
│   └── Stylelabs.Scripting.dll
├── references
│   ├── Action.csx
│   ├── Base.csx
│   ├── MediaProcessing.csx
│   ├── Shared.csx
│   ├── UserPostRegistration.csx
│   ├── UserPreRegistration.csx
│   ├── UserSignIn.csx
Note

The files on the working folder might change depending on the Content Hub version of the instance you are connected to.

Create your Shared script

  1. Open your working folder in Visual Studio Code.
  2. Create a new file with extension .csx at the root of the working folder. The name of the file will be the name of your script.
  3. Open the file and add the following header:

    #load "./references/Shared.csx"
    /**------------ Include above to support intellisense on Content Hub types in editor ----------------**/
    // Script Start
    
    Important

    The script's header will determine the script's type. All lines in the header are required.

  4. Save the file. At this point, you should have Intellisense.

  5. Start the script Watcher:

    Run command

    ch-cli scripting watch -f <your-folder-path>
    Note

    You can run this command from Visual Studio Code's terminal.

    At this point, your Shared script has been created on the Content Hub instance you are connected to.

  6. Work on your script

    Note

    Every time you save your script, the script Watcher will compile and publish it.

  7. Enable your Shared script.

    Run command

    ch-cli scripting enable -n <your-script-name>

Reference your Shared script from other scripts

Reference your Shared script by its name, for example:

#load "./references/Action.csx"
/**------------ Include above to support intellisense on Content Hub types in editor --------------**/
// Script Start

#load "my-shared-script.csx"

...

Happy Coding!

Can we improve this article ? Provide feedback