Skip to main content

Creating and Using Modules

QuickJS supports ES6 modules with import and export statements. This tutorial shows how to create and use both JavaScript and native C modules.

JavaScript Modules

1

Create a module

Create fib_module.js with an exported function:
The export keyword makes the fib function available to other modules.
2

Import and use the module

Create hello_module.js that imports the function:
The import statement loads the module and destructures the exported function.
3

Run the module

Execute with the -m flag to enable module mode:
Expected output:
QuickJS auto-detects module mode based on import/export statements, so the -m flag is usually optional.

Native C Modules

You can also import native modules compiled as shared libraries.
1

Create a cross-platform import

Create test_fib.js that imports a native module:
Key features:
  • Uses qjs:os to detect the platform
  • Dynamically imports .so on Unix or .dll on Windows
  • Uses await import() for dynamic imports
2

Compile the native module

First, create the C module (see Native Functions guide).Then compile it as a shared library:On Linux/macOS:
On Windows:
3

Run with standard library

Execute with the --std flag to enable the qjs:os module:
Expected output:

Built-in Modules

QuickJS provides built-in modules accessible with the qjs: prefix:
  • qjs:os - Operating system interfaces (file I/O, processes, etc.)
  • qjs:std - Standard utilities (console, setTimeout, etc.)
  • qjs:bjson - Binary JSON encoding/decoding
Example:
Enable built-in modules with the --std flag:

Module Resolution

QuickJS resolves module specifiers as follows:
  1. Relative paths (./, ../) - Resolved relative to the importing file
  2. Built-in modules (qjs:*) - QuickJS standard library
  3. Absolute paths (/path/to/module) - Loaded directly
  4. Bare specifiers (module-name) - Not supported by default

Dynamic Imports

Use await import() for runtime module loading:

Compiling Modules

Compile a module to bytecode:
The -m flag tells qjsc to compile as an ES6 module.

Next Steps