ES Modules

js-cgi supports standard ES modules with import and export. Module syntax is automatically detected when your script contains these keywords.

Basic Usage

// utils.js
export function greet(name) {
    return `Hello, ${name}!`;
}

export function formatDate(date) {
    return date.toISOString().split('T')[0];
}
// index.js
import { greet, formatDate } from "./utils.js";

print(greet("World"));
print(formatDate(new Date()));

Default Exports

// config.js
export default {
    siteName: "My App",
    version: "1.0.0"
};
// index.js
import config from "./config.js";
print(config.siteName);

Named and Default Together

// db.js
export default function connect() { /* ... */ }
export function query(sql) { /* ... */ }
export function close() { /* ... */ }
// index.js
import connect, { query, close } from "./db.js";

Re-exporting

// lib/index.js
export { greet } from "./utils.js";
export { query } from "./db.js";

Path Resolution

Module paths are resolved relative to the script's directory:

  • ./utils.js — same directory
  • ./lib/helpers.js — subdirectory
  • ../shared/common.js — parent directory
  • /var/www/js/lib/core.js — absolute path

When to Use Modules vs include()

Use CaseApproach
Utility functions, helpersES Modules
Database access layerES Modules
HTML templates, layoutsinclude()
Shared headers/footersinclude()
Configuration objectsEither

Important Notes

  • Modules run in strict mode automatically
  • print() works inside modules
  • Use globalThis to share values from modules to the global scope if needed
  • Module files must use the .js extension in the import path
Was this page helpful?