Open Lennart-Lucas opened 8 months ago
Did you find how to import ?
Did you find how to import ?
Not really. At the moment I just do what I stated above. I have one script which puts all commonly used variables & methods in the params.variables, and in the next script I get them from there. It isn't ideal but it works.
I've been able to kind of get this working, but it has a limitation: The included script you want to require has to be present when Obsidian loads, and if you modify it, you have to reload the app for changes to get picked up; a normal macro script will get reloaded if it changes, but the require
'd script will remain as it was when Obsidian loaded. Reload without saving
is sufficient for picking up changes to your utility module.
Here's how I got this working:
require
the script in your other files using the absolute filesystem path.Here's an example; I created a JS file at <vault dir>/config/scripts/quickadd/quickadd_utils/quickadd_utils.js
that exports a module with a function I use a lot to get the currently focused file from the sidebar:
module.exports = {
getFileExplorerFocusedFile: (app) => {
const fileExplorerLeaf = app.workspace.getLeavesOfType('file-explorer');
if (fileExplorerLeaf.length !== 1) {
console.log("archive.js -- File Explorer Not Available.");
return;
}
const fileExplorerView = fileExplorerLeaf[0].view;
if (fileExplorerView === null) {
console.log("archive.js -- No file explorer view available.");
return;
}
const focusedFile = fileExplorerView.tree.focusedItem;
if (focusedFile === null) {
console.log("archive.js -- No file selected.");
return;
}
const path = focusedFile.file !== null ? focusedFile.file.path : null;
if (path === null) {
console.log("archive.js -- Unable to get path from focused file.");
return;
}
return app.vault.getAbstractFileByPath(path);
}
}
I have another javascript file that is loaded as a userscript in a QuickAdd Macro, and I can require it like so:
const utils = require(`${app.vault.adapter.basePath}/config/scripts/quickadd/quickadd_utils`);
module.exports = async (params) => {
const focusedFile = utils.getFileExplorerFocusedFile(params.app);
console.log(`focused file from utils module: ${focusedFile}`);
}
I might be missing something obvious, but is it possible to have functions and constants defined in other files and import them into the quickadd macro code files?
For instance I have a function used to format numbers, which is used in a number of macro's. But the only way of having a single instance of a function, but using it in multiple macro's seems to be putting it in the params.variables, passing it to the next script and accessing it there? Which seems a bit convoluted?
Is there a more straightforward way of handling this?