Creating Templater User Functions that use node modules?

Things I have tried

  • Searching Templater Docs
  • Searching Obsidian Forum for “node_modules” + “templater”, and variations on that.

What I’m trying to do

I’m trying to write a somewhat complex user function that will be used with the Templater plugin. But i’m hitting a wall when trying to import npm packages… i’m wondering if anyone else has some insight on this?

As part of the Templater docs it states

Scripts should follow the CommonJS module specification, and export a single function.
Let’s have an example with our previous script my_script.js:

function my_function (msg) {
    console.log("Message from my script:", msg);
module.exports = my_function;

Templater will then load all JavaScript (.js files) scripts in the Scripts folder.
You will then be able to call your scripts as user functions. The function name corresponds to the script file name.

So I initialised a node project:

npm init

And was building out my project fine and then when it came to installing an external package… Templater reads all the packages in node_modules and errors because those modules don’t follow CommonJS (I assume)

Package I tried to install

npm install --save gray-matter

Has anyone else tried using a npm package and know how I might solve this? I’m guessing I could maybe move my node_modules to a different directory than the one containing my user functions, but not 100% how they then get picked up etc.

Thanks for any help or advice

If you are going so far as to include external libraries I’d suggest just building your own personal plugin and putting whatever you want it there. It’s pretty easy using the sample plugin and provides all the build tooling required.

Basically you can’t import directly into a templater user script. You would need to write your code and then have a build step that brings everything into a single JS file and exposes as a cjs module. Afaik no one has attempted this. It is basically what building a plugin does, so probably easier to go that route.

1 Like

The only other thing I can think of is to import from But I’m not sure they use CJS (I know you can get a UMD import…)

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.