Lesson 10 of 16

Modules & Packages

import, stencil.json, stencil install

download this lesson (.md) ↓ all lessons

10. Modules & Packages

import — split code across files

import "file.st"; runs another file's top-level definitions (functions, classes, stencils, variables) so you can use them.

mathx.st:

func square(x) { return x * x; }
func cube(x) { return x * x * x; }
class Counter {
    func init() { this.n = 0; }
    func tick() { this.n = this.n + 1; return this.n; }
}

main.st (same folder):

import "mathx.st";
print(square(6));   // 36
let c = Counter();
c.tick();
print(c.tick());    // 2

Paths are resolved relative to the importing file. Imports are de-duplicated, so importing the same file twice is safe.

Packages — install reusable modules

A project can declare dependencies in stencil.json:

{
  "name": "myapp",
  "version": "0.1.0",
  "dependencies": {
    "greet": { "path": "../greetlib" },
    "utils": { "git": "https://github.com/user/utils" }
  }
}
  • path — a local folder
  • git — a git repository (cloned with git)

Install them:

stencil install

This copies/clones each dependency into stencil_modules/. Then import by name:

import "greet";     // resolves to stencil_modules/greet/main.st (or greet.st)
print(selamla("World"));

Starting a new package

stencil init        # creates a starter stencil.json

Resolution order for import "name"

  1. A file at that path relative to the current file (import "lib/util.st").
  2. For a bare name: stencil_modules/name.st, then stencil_modules/name/main.st, then stencil_modules/name/name.st — searching up parent folders.

Next: Standard Library