Expose `obsidian` module to be used outside plugins

Use case or problem

Obsidian API has some useful functions that seems to be able to use only within plugins using const obsidian = require('obsidian');.

Sometimes those functions are needed to use ad-hoc, from Developer Tools, dataviewjs, Templater etc, but at this stage I see no way to reach those functions and require('obsidian') gives Uncaught Error: Cannot find module 'obsidian';

Proposed solution

add a global variable such as window.app.module to be able to reach the module outside plugins.

Added a temporary workaround

if (!app.module) {
    const dir = `${app.vault.configDir}/plugins/extract-module`;
    app.plugins.manifests['extract-module'] = { dir: dir };
    await app.vault.adapter.mkdir(dir);
    const moduleFunc = () => {
        app.module = require('obsidian');
        exports.default = app.module.Plugin;
    };
    await app.vault.adapter.write(`${dir}/main.js`, `(${moduleFunc})();`);
    await app.plugins.loadPlugin('extract-module');
}
3 Likes

this should be posted in developer and api

Built a plugin to make require() working: GitHub - mnaoumov/obsidian-fix-require-modules: Obsidian Plugin that fixes `require()` calls for the built-in modules

1 Like