Logo Trilium Rocks!

Structure of a script

Bundles#

Scripts are formed into a bundle and executed with a specific eval context. This bundle is wrapped in an async IIFE, that means scripts can use await at the top level without issue. It also means that using var won't pollute the global scope. But… you shouldn't be using var anyways. Lastly, it allows Trilium to provide each script a specific context of psuedo-globals as well as a set of parameters to the IIFE.

Variables#

Since these bundles are IIFEs, Trilium does make use of passing parameters to create a scoped set of pseudo-globals for each script. Here are what's passed to each script:

  • exports - empty object just like in node
  • module - object containing only exports just like in node
  • require - a fake require function that allows you to import child notes (see below)
  • api - an instance of the frontend api scoped specifically to this script

Additionally, if any of the child notes are also scripts but they export something via module.exports they will be included in the passed parameters as the title of the note removing any special characters (e.g. highlight.min.js becomes highlightminjs). This is used as an alternative to using require. You can read more about how to do this in the next section.

Exports#

Scripts aren't actually required to export anything if they don't want to, and Trilium does not use the export beside providing it to the parent note. The only exception to this rule is Widgets which we will get to later on.

Globals#

Since the environment is still a web browser and JavaScript, there's no real way to fully encapsulate these scripts so they still have full access to window/global object and can access anything that is typical of a web browser. If you go exploring in the developer tools you may see that Trilium adds some globals to the window beyond what is typical. But these are undocumented and therefore not stable or guaranteed. One that may be of interest to specific or niche plugins would be the glob global that is available on both web and desktop versions of Trilium and contains some information that can be helpful in certain situations.