JavaScript API
Farm exposes its Node.js API from @farmfe/core for dev servers, production builds, watch mode, preview servers, config loading, environment loading, and direct compiler access.
npm add @farmfe/core@latestyarn add @farmfe/core@latestpnpm add @farmfe/core@latestbun add @farmfe/core@latestTop-level helpers
start
start(options?: FarmCliOptions & UserConfig): Promise<void>
Starts the Farm dev server. It resolves config in dev / development mode, creates the server, starts listening, compiles the project, and prints server URLs.
import { start } from '@farmfe/core';
import react from '@farmfe/plugin-react';
await start({
compilation: {
input: { index: './index.html' },
output: { publicPath: '/dist/' }
},
server: { port: 6532 },
plugins: [react()]
});
build
build(options?: FarmCliOptions & UserConfig): Promise<void>
Resolves config in build / production mode, creates a compiler, compiles once, and writes resources to disk.
import { build } from '@farmfe/core';
await build({
compilation: {
input: { index: './index.html' },
output: { path: 'dist' }
}
});
watch
watch(options?: FarmCliOptions & UserConfig): Promise<void>
Builds in watch mode and rebuilds when watched files change. If lazy compilation is enabled, Farm also starts the lazy-compilation server.
import { watch } from '@farmfe/core';
await watch({ compilation: { output: { path: 'dist' } } });
preview
preview(options?: FarmCliOptions & UserConfig): Promise<void>
Starts a preview server for existing production assets.
import { preview } from '@farmfe/core';
await preview({
server: {
preview: { port: 9000, distDir: 'dist' }
}
});
clean
clean(rootPath: string, recursive?: boolean): Promise<void>
Removes Farm persistent-cache files for the resolved project. Pass recursive: true to search nested node_modules folders.
import { clean } from '@farmfe/core';
await clean(process.cwd());
Config and environment helpers
defineConfig
import { defineConfig } from '@farmfe/core';
import react from '@farmfe/plugin-react';
export default defineConfig({
plugins: [react()]
});
resolveConfig
resolveConfig(
inlineConfig?: FarmCliOptions & UserConfig,
command?: 'dev' | 'build' | 'watch',
mode?: string
): Promise<ResolvedUserConfig>
Use resolveConfig before calling lower-level APIs such as createCompiler.
import { createCompiler, resolveConfig } from '@farmfe/core';
const resolved = await resolveConfig({ root: process.cwd() }, 'build', 'production');
const compiler = createCompiler(resolved);
loadEnv
loadEnv(
mode: string,
envDir: string,
prefixes?: string | string[]
): [env: Record<string, string>, existsEnvFiles: string[]]
Loads .env, .env.local, .env.${mode}, and .env.${mode}.local from envDir. Prefixes default to ['FARM_', 'VITE_'].
import { loadEnv } from '@farmfe/core';
const [env, files] = loadEnv('development', process.cwd());
Dev server APIs
Server.createServer
Server.createServer(options?: FarmCliOptions & UserConfig): Promise<Server>
Creates and initializes a development server. Call listen() to start the HTTP server and initial compilation.
import { Server } from '@farmfe/core';
const server = await Server.createServer({ server: { port: 9000 } });
await server.listen();
Server instance methods
| Method | Description |
|---|---|
listen(): Promise<void> | Start listening, compile, and set up watch behavior. |
restart(): Promise<Server> | Close the current server and create a replacement from the same inline config. |
restartServer(): Promise<void> | Restart and print URLs when host/port changes. |
getCompiler(): Compiler | undefined | Return the current compiler after the server has started compiling. |
setCompiler(compiler: Compiler): void | Replace the server compiler instance. |
addWatchFile(root: string, deps: string[]): void | Add extra files to watch through the compiler. |
close(): Promise<void> | Close watcher, WebSocket server, and HTTP server. |
printUrls(): void | Print resolved server URLs after listen(). |
PreviewServer
preview() is the high-level API for preview mode. For lower-level control, PreviewServer is exported from @farmfe/core via the server module exports.
Compiler APIs
Create compilers from resolved config:
import { createCompiler, resolveConfig } from '@farmfe/core';
const config = await resolveConfig({}, 'build', 'production');
const compiler = createCompiler(config);
await compiler.compile();
| Method | Description |
|---|---|
compile(): Promise<void> | Run one compilation. Uses sync compilation internally when FARM_PROFILE is set. |
compileSync(): void | Run compilation synchronously. |
update(paths, sync?, ignoreCompilingCheck?, generateUpdateResource?): Promise<JsUpdateResult> | Incrementally update modules. paths are { path, type } items where type is added, updated, or removed. |
traceDependencies(): Promise<unknown> | Return config/module dependency tracing from the native compiler. |
traceModuleGraph(): Promise<TracedModuleGraph> | Return a traced module graph. |
hasModule(resolvedPath: string): boolean | Check whether a resolved path is in the module graph. |
getParentFiles(idOrResolvedPath: string): string[] | Return parents/importers of a module. |
resources(): Record<string, Buffer> | Return compiled resource buffers by resource name. |
resource(path: string): Buffer | Return one compiled resource buffer. |
resourcesMap(): Record<string, Resource> | Return full resource metadata by resource name. |
writeResourcesToDisk(): void | Write resources and run the writeResources plugin hook. |
callWriteResourcesHook(): void | Run JS plugin writeResources hooks without writing resources. Used by dev mode when server.writeToDisk is disabled. |
removeOutputPathDir(): void | Remove the configured output directory. |
resolvedWatchPaths(): string[] | Return watched module paths from the compiler. |
resolvedModulePaths(root: string): string[] | Return resolved module paths under root. |
transformModulePath(root: string, path: string): string | Normalize a module path to a filesystem path. |
onUpdateFinish(callback): void | Queue a callback after an update finishes. |
outputPath(): string | Return the resolved output directory. |
addExtraWatchFile(root: string, paths: string[]): void | Add extra watch files. |
stats(): unknown | Return native compiler stats. |
waitForCompileFinish(): Promise<void> | Wait for an in-progress compile to finish. |
invalidateModule(moduleId: string): void | Invalidate one module in the native compiler. |
writeMetadata(name, data, options?): void | Store JSON-serialized metadata for plugins/APIs. |
readMetadata(name, options?): unknown | Read metadata written with writeMetadata. |
readMetadataByScope(scope: string): unknown[] | Read metadata entries by scope. |
createInlineCompiler
createInlineCompiler(
config: ResolvedUserConfig,
options?: ResolvedCompilation
): Compiler
Creates a compiler by overriding the resolved compilation object inline.
Farm