Skip to main content

ES6 Modules

QuickJS has full support for ES6 modules, including dynamic imports, import attributes, and custom module loaders.

Module Loader Functions

JS_SetModuleLoaderFunc

Set the module loader for a runtime.

Function Type Definitions

Parameters

  • rt - The JavaScript runtime
  • module_normalize - Function to normalize module names (can be NULL for default)
  • module_loader - Function to load modules
  • opaque - User data passed to loader functions

Example: Basic Module Loader

From quickjs-libc:

Import Attributes Support

JS_SetModuleLoaderFunc2

Set module loader with import attributes support.

Function Type Definitions

Example: JSON Module Import

C Modules

JS_NewCModule

Create a new C module.

Parameters

  • ctx - The JavaScript context
  • name_str - Module name
  • func - Initialization function (called when module is first imported)

Returns

Returns a module definition, or NULL on error.

Example: Creating a C Module

From examples/fib.c:

JS_AddModuleExport

Declare a module export (before instantiation).

JS_AddModuleExportList

Declare multiple module exports.

JS_SetModuleExport

Set the value of a module export (after instantiation).

JS_SetModuleExportList

Set multiple module export values.

Module Metadata

JS_GetImportMeta

Get the import.meta object for a module.

Example: Setting import.meta

From quickjs-libc:

JS_GetModuleName

Get the name of a module.

JS_GetModuleNamespace

Get the namespace object of a module.

Dynamic Import

Dynamic imports are handled automatically by the module loader:
The module loader function is called when the import executes.

Complete Example

Notes

  • Module loader functions are called per runtime, not per context
  • Use JS_EVAL_TYPE_MODULE flag when evaluating module code
  • C modules can be dynamically loaded as .so/.dll files
  • Import attributes (formerly “import assertions”) are supported
  • The default normalizer resolves relative paths
  • import.meta.url and import.meta.main are commonly set by loaders