Templater - How to import js function from one file into other file?

As title says with examples below how to import function Bar in Foo?

I tried just doing an import but it fails with “Cannot use import statement outside a module”
Then I figured I should probably do something like module.import in some way but dunno how.

Example files:

Foo.js

Do import somehow?

function Foo() {
    Bar();
}
module.exports = Foo;

Bar.js

function Bar() {
    console.log("bar");
}
module.exports = Bar;

On a sidenote I tried adding topic tags for js, javascript, code, etc but there were no options for them so they could not be added.

Some of the Templater user scripts examples suggest to pass the tp as an argument, and that allows for automatic imports as well, as then the functions are available through the user scripts.

With that in mind I made the following files:

foo.js

function foo(tp) {
 
  console.log('foo');
  return "foo" + tp.user.bar(tp);
}

module.exports = foo

bar.js

function bar(tp) {
 console.log("bar");
 return "bar"
}

module.exports = bar

Some random test file

<%+ tp.user.foo(tp) %>

Which indeed returned “foobar” as expected, when I’m previewing it. I’m getting some type error thingy, seen in the console, but it does do the expected stuff.

Regards,
Holroy

Thanks for a quick reply!

This is an interesting idea and I certainly would not mind doing it like this.

I’m a little uncertain as to whether I should check it as solution or not since it technically did not solve the question of how to import. I think I will let it be for a few days and see if somebody else has more input otherwise I will just mark this answer as solution.

1 Like