Import statement
The import statement is used on module-level definitions, and has two distinct meanings depending on context. If it is succeeded by two strings (e.g. import "Main" "Example"), then it is declaring that as an external import of the Wasm module. Otherwise, it can import items exported from another Water file module into the current file.
External imports
As explained above, the import "Main" "Example" syntax can be used on a variety of definitions (e.g. global variables, functions, memories, etc.) to declare them as imports to the Wasm module. By default, Wasm modules (and by extension, Water code) is fully sandboxed from the outside world. External imports allow the host environment to expose certain functionality to the Wasm module, to e.g. make network requests, create HTML elements, etc.
For more complete examples, have a look at the examples tab, where it is shown how you can provide custom imports to the compiled Wasm module to expose various functions, variables, memories, etc. to Water code.
Importing from file
You can import any identifier which was exported by that module. This works exactly the same as it does in Javascript/Typescript modules. The importing syntax is also the same, and also supports unaliased wildcard imports (importing all exported identifiers from a module without an "as"). Here is an overview of the allowed syntaxes:
- import * from "Example.water";
- import {OriginalName as AliasedName, Something, Thing as AliasedThing} from "Example.water";
- import DefaultExport from "Example.water";
- import * as ImportAllAlias from "Example.water";
- import Thing, {OtherThing} from "Example.water";
- import Something, * as Everything from "Example.water";
Important note about using memories and tables
Note that if more than one file wants to have access to some memory / table / etc, then it also needs to be exported, and imported into the other files. In other words, memory and table declarations are not necessarily global in Water, even though they might be in raw Wasm.
This decision was made because every other part of Water file modules is only scoped to that file (unless exported and then imported), so this would potentially be an outlier and as such, potentially unexpected behaviour.
Note that certain functions which have an optional memory immediate (e.g. i32.load) would also fail if no memory is imported, even if no memory immediate was provided. When no memory immediate is provided, they default to the first memory declared in that file, which may be coming from an import. Because this might have confusing semantics, avoid using these functions without explicitly providing the memory immediate, unless it is absolutely clear which memory is going to be used.