Third party modules and libraries

You can load third party Common.js-type modules via the require() function.

Load an external module in one of the following ways:

Loading a single file

You can load a single file written in Common.js format by copying the file into the script folder and requiring it.

For example, if the file is myLibrary.js and it is in the script folder, add the following lines to the script:

const myLibrary = require('./myLibrary.js');

myLibrary.myFunc1();

myLibrary.js then contains:

module.exports = {
   myFunc1(){
   },
…
};

Required files that are not part of the files section in the rts.yml (the section containing the Additional files) cannot use the load namespace directly. You therefore need to pass the load namespace into the required module yourself.

For example:

const myLibrary = require('./myLibrary.js')(load);
myLibrary.myFunc1();

myLibrary.js then contains:


module.exports = function(load){
  return {
   myFunc1(){
   },
  …
};
};

When requiring a JavaScript file, standard Node.js syntax (module.exports) is applied. A JSON file can be required directly, without any additional syntax.

For example:

const someData = require('data.json');

data.json then contains:

{
  "user":"bob",
  "age":36
}
Loading an npm module

You can load an npm module as long as it can run on any JavaScript runtime (namely, a browser).

To use this method, Node.js must be installed on your computer.

For example, use the following procedure to install the lodash library (https://www.npmjs.com/package/lodash) :

  1. Open the command prompt and navigate to the script folder.

  2. Type npm install lodash and wait for the process to finish. The node_modules folder is created in the script folder.

  3. In your script, add the following line: (Do not add the .js extension)

    const lodash = require('lodash');

Tip: If Node.js is not installed, you can download an npm module using standalone npm or using a third party package manager such as Yarn.

Managing multiple modules via package.json (advanced use case)

If you are using multiple third-party npm modules and want to manage their dependencies, you can create a package.json file and manage all the dependencies with npm.

To use this method, Node.js must be installed on your computer.

  1. Create the package.json file using the npm init command as follows:

    1. Open the command prompt and change to the script folder.

    2. Type npm init --yes and wait for the process to finish.

  2. To install any supported package, type npm install <packagename> and wait for the process to finish. The node_modules folder is created in the script folder.

  3. In your script, add the following line (Do not add the .js extension):

    const <packagename> = require('<packagename>');

Tip: If Node.js is not installed, you can download an npm module using standalone npm or using a third party package manager such as Yarn.

Back to top