Why can't I use a function in a chapter even though I imported it at the start of my main file?

This is actually possible to do:

#let my-import(pkg) = {
  import pkg as p
  p
}

#my-import("@preview/example:0.1.0").add(1, 2)

One problem is that this only works for package imports; for files you’d run into path problems, such as here: Why are paths always relative to the current file? The other problem is of course that, unless this was built-in, you’d still need to import or write that function yourself…


Personally I think the way to allow this is to allow specifying an actual prelude somehow. That “somehow” would probably be the typst.toml file that already contains metadata for packages, and make it more appropriate for documents in addition to packages (and templates).

Using a prelude file for this would mean that the regular Typst import and let statements could still be used, they’d very naturally specify the package versions to use at a single location, and not require completely new concepts.


The downside in general of any such approach is that Typst code becomes less “copy-pasteable”: right now, you can look at the file and find everything that the code you’re copying needs; either directly there or in it imports. (Well there’s already one tiny caveat to that: your file may require a specific version of Typst to compile, which is not written down in every file.)

1 Like