This is part of a cookbook of tips and tricks in Obsidian by readwithai (X, blog)
It is possible to do JavaScript scripting in Obsidian in various ways (including using my plugin, Plugin REPL) and this can do a lot of things. However, for some more complicated tasks it can be nice to use libraries that other people have created, which tend to be uploaded as an NPM library. Because of how Obsidian works - even though Obsidian has its own npm modules provided in a node_modules directory you cannot add to these modules. A work around is needed.
How plugins do it
One approach is to use a plugin. The way that plugins work is use a JavaScript bundler to include the source code for modules in the main.js that a plugin provides. This plugin can then provide access to this module - although it normally uses it internally. A nice trick here is to use the following syntax in TypeScript:
import * as name from 'name'
...
this.name = name
You can then hang name of your plugin, and then get access to it from Obsidian using:
app.plugins.plugins["my-id"].name
If you just want something that works
However, you probably donโt want to create your own plugin every time you use a library. If you are doing your Obsidian JavaScript scripting with Plugin REPL then plugin repl provides a system to use plugins, plugin REPL imports. With this you can: check out a repo, add the NPM library to a list, run a command, and then you can use a funciton replRequire to get at the NPM library.
You can likely do something similar with user scripts in Templater.
Finishing up
I hope this is useful. If you found this intereting I might suggest you:
Have a look at some more recipes in my Obsidian cookbook
Read about scripting in Obsidian.
Read my somewhat academic review of note taking in Obsidian.
You can also follow me on X, where I write about various things, or follow my blog where I mostly write about tools for reading and research.