Load separate JS files to use in DataviewJS

Dataview comes in two syntactic flavours, Dataview Query Language (DQL) and DataviewJS. Both can be used in code blocks and as inline expressions; both have same functionalities. I prefer the latter since I'm familiar with writing JS.

More info in the docs: https://blacksmithgu.github.io/obsidian-dataview/#querying

Write DV code in code block

By default, we run the DataviewJS code in a code block marked dataviewjs.

dv.taskList(dv.pages('#daily').file.tasks.where(t => !t.completed));

Load DV code from JS file

Alternatively, we can create a JS file in our vault...

// _assets_/dv/unfinished-tasks.js
dv.taskList(dv.pages('#daily').file.tasks.where(t => !t.completed));

...and call it from the dataviewjs code block in our note.

dv.view("_assets_/dv/unfinished-tasks");

The path is relative to our vault root directory without a leading slash.

Customizing with input argument

dv.view accepts an optional 2nd argument that is passed as input.

// _assets_/dv/unfinished-tasks.js
dv.taskList(dv.pages(input ?? undefined).file.tasks.where(t => !t.completed));

Show all notes with unfinished tasks.

dv.view("_assets_/dv/unfinished-tasks");

Show notes tagged #daily with unfinished tasks.

dv.view("_assets_/dv/unfinished-tasks", "#daily");

Show notes from the Work folder with unfinished tasks.

dv.view("_assets_/dv/unfinished-tasks", "'Work'");

This is regular JS, so the input argument can be any accepted JS type.

Advantages

  • Reusable across notes
  • Separation of concern between note content and utility/helper code; keep note content succint (in case of long DV code)
  • Better editing experience (syntax highlighting, Intellisense/autocomplete in your favourite code editor, formatting, etc)
  • Easier to back up and share the DV code

To me, this was the clincher that converted me to a happy Dataview user.


In: Obsidian MOC

Links to this note

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.