OpenComponents Server-Side Logic Compiler
oc-server-compiler is a foundational module within the OpenComponents (OC) micro-frontends framework, designed specifically to compile the server-side logic (`server.js` or `entry.server.ts`) of isomorphic OC components. These components encapsulate HTML, CSS, JavaScript, and optional server-side code, allowing for universal rendering. This package facilitates the transformation of a component's server-side JavaScript/TypeScript into an executable format, typically used by an OC registry for server-side rendering or by the OC CLI during component development and publishing. It is a core utility that ensures the component's data-fetching and model-composition logic is correctly processed for deployment. The current stable version is 4.0.0. While the OpenComponents project itself follows semantic versioning with releases driven by feature development and bug fixes, this compiler module's updates are tightly coupled with the broader framework's evolution. A key differentiator of OpenComponents is its language-agnostic approach to consumption, allowing components compiled by this module to be rendered and consumed by various backend technologies (e.g., C#, PHP, Java, Go) without requiring Node.js on the edge.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'params')
cause The `context` object provided to a component's server-side `data` function is missing expected properties, such as `params`, which typically come from a client request.fixWhen calling the `data` function directly or through a mock, ensure the `context` object is fully populated with all expected properties, including `params` and `headers`, as defined by the OpenComponents runtime environment. -
Error: Component server.js compilation failed: SyntaxError: Unexpected token 'export'
cause The `server.js` file uses ESM `export` syntax (e.g., `export function data() { ... }`) but is being treated as CommonJS by the compiler or the Node.js runtime.fixIf your `server.js` is intended to be an ESM module, ensure your `package.json` specifies `"type": "module"` in the component directory, or explicitly use `.mjs` extension. Otherwise, use CommonJS `module.exports = { ... };` syntax for compatibility. -
Error: Cannot find module 'some-external-dependency' from '...' at Function.Module._resolveFilename
cause A server-side dependency declared in the component's `package.json` (or required in `server.js`) cannot be resolved during compilation or runtime.fixEnsure all server-side dependencies for the component are correctly installed (e.g., `npm install` in the component's directory) and accessible in the compilation environment. If publishing, confirm the registry supports resolving or bundles these dependencies.
Warnings
- breaking Starting with OpenComponents v0.49.0, Node.js versions 8 and 10 are no longer supported. `oc-server-compiler` as a core module in version 4.0.0 requires Node.js 12 or higher, with Node.js 18+ being recommended for optimal performance and security. Running on older Node.js versions will likely lead to errors.
- gotcha The `oc-server-compiler` is part of the OpenComponents ecosystem and is not a general-purpose JavaScript/TypeScript compiler. It expects specific input structures conforming to the OpenComponents component specification (e.g., `server.js` within an OC component directory). Attempting to compile arbitrary JavaScript or TypeScript files directly without the correct context will result in errors.
- deprecated Older OpenComponents templates (e.g., specific Handlebars or Jade versions) might be compiled with older internal compiler logic or rely on deprecated features. While `oc-server-compiler` 4.0.0 handles modern ES6 templates by default and aims for backward compatibility, using outdated template syntax in conjunction with server-side logic could lead to unexpected behavior or compilation warnings.
Install
-
npm install oc-server-compiler -
yarn add oc-server-compiler -
pnpm add oc-server-compiler
Imports
- compile
const { compile } = require('oc-server-compiler');import { compile } from 'oc-server-compiler'; - CompilerOptions
import type { CompilerOptions } from 'oc-server-compiler'; - OcCompiler
import OcCompiler from 'oc-server-compiler';
Quickstart
import { compile } from 'oc-server-compiler';
import * as fs from 'fs';
import * as path from 'path';
async function runCompilation() {
const componentPath = path.join(process.cwd(), 'my-component');
const serverJsPath = path.join(componentPath, 'server.js');
const componentPackageJsonPath = path.join(componentPath, 'package.json');
// Create a dummy component directory and files for demonstration
if (!fs.existsSync(componentPath)) {
fs.mkdirSync(componentPath, { recursive: true });
}
fs.writeFileSync(serverJsPath, `
module.exports = {
data: (context, callback) => {
console.log('Executing server.js data function...');
callback(null, { name: context.params.name || 'World', version: '4.0.0' });
}
};
`);
fs.writeFileSync(componentPackageJsonPath, `
{
"name": "my-component",
"version": "1.0.0",
"oc": {
"files": {
"data": "server.js",
"template": {
"src": "template.html",
"type": "handlebars"
}
}
}
}
`);
try {
// The compile function takes the component's directory path
// and returns compiled assets or metadata.
const result = await compile({
componentPath: componentPath,
minify: true,
verbose: process.env.DEBUG === 'true'
});
console.log('Compilation successful! Output:');
console.log(JSON.stringify(result, null, 2));
// Expected result might include: { entry: 'compiled/server.js', hash: '...', externals: [] }
} catch (error) {
console.error('Compilation failed:', error);
} finally {
// Clean up dummy files
fs.unlinkSync(serverJsPath);
fs.unlinkSync(componentPackageJsonPath);
fs.rmdirSync(componentPath);
}
}
runCompilation();