What worked for me is to use dv.io.load
to load the JavaScript file and use dv.executeJs
to execute it.
dv.executeJs(await dv.io.load("Scripts/folder/filename.js"))
OLD
Another solution to this seems to be wrapping the entire script in the function:
dv.executeJs(`
// write your code here
`)l
Reference: Dataview: reuse DQL queries?