Skip to main content
FarmFarm
Version: 2.x (Latest)
On this page

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.

sh
npm add @farmfe/core@latest
sh
yarn add @farmfe/core@latest
sh
pnpm add @farmfe/core@latest
sh
bun add @farmfe/core@latest

Top-level helpers

start

ts
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.

ts
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

ts
build(options?: FarmCliOptions & UserConfig): Promise<void>

Resolves config in build / production mode, creates a compiler, compiles once, and writes resources to disk.

ts
import { build } from '@farmfe/core';

await build({
  compilation: {
    input: { index: './index.html' },
    output: { path: 'dist' }
  }
});

watch

ts
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.

ts
import { watch } from '@farmfe/core';

await watch({ compilation: { output: { path: 'dist' } } });

preview

ts
preview(options?: FarmCliOptions & UserConfig): Promise<void>

Starts a preview server for existing production assets.

ts
import { preview } from '@farmfe/core';

await preview({
  server: {
    preview: { port: 9000, distDir: 'dist' }
  }
});

clean

ts
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.

ts
import { clean } from '@farmfe/core';

await clean(process.cwd());

Config and environment helpers

defineConfig

ts
import { defineConfig } from '@farmfe/core';
import react from '@farmfe/plugin-react';

export default defineConfig({
  plugins: [react()]
});

resolveConfig

ts
resolveConfig(
  inlineConfig?: FarmCliOptions & UserConfig,
  command?: 'dev' | 'build' | 'watch',
  mode?: string
): Promise<ResolvedUserConfig>

Use resolveConfig before calling lower-level APIs such as createCompiler.

ts
import { createCompiler, resolveConfig } from '@farmfe/core';

const resolved = await resolveConfig({ root: process.cwd() }, 'build', 'production');
const compiler = createCompiler(resolved);

loadEnv

ts
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_'].

ts
import { loadEnv } from '@farmfe/core';

const [env, files] = loadEnv('development', process.cwd());

Dev server APIs

Server.createServer

ts
Server.createServer(options?: FarmCliOptions & UserConfig): Promise<Server>

Creates and initializes a development server. Call listen() to start the HTTP server and initial compilation.

ts
import { Server } from '@farmfe/core';

const server = await Server.createServer({ server: { port: 9000 } });
await server.listen();

Server instance methods

MethodDescription
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 | undefinedReturn the current compiler after the server has started compiling.
setCompiler(compiler: Compiler): voidReplace the server compiler instance.
addWatchFile(root: string, deps: string[]): voidAdd extra files to watch through the compiler.
close(): Promise<void>Close watcher, WebSocket server, and HTTP server.
printUrls(): voidPrint 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:

ts
import { createCompiler, resolveConfig } from '@farmfe/core';

const config = await resolveConfig({}, 'build', 'production');
const compiler = createCompiler(config);
await compiler.compile();
MethodDescription
compile(): Promise<void>Run one compilation. Uses sync compilation internally when FARM_PROFILE is set.
compileSync(): voidRun 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): booleanCheck 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): BufferReturn one compiled resource buffer.
resourcesMap(): Record<string, Resource>Return full resource metadata by resource name.
writeResourcesToDisk(): voidWrite resources and run the writeResources plugin hook.
callWriteResourcesHook(): voidRun JS plugin writeResources hooks without writing resources. Used by dev mode when server.writeToDisk is disabled.
removeOutputPathDir(): voidRemove 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): stringNormalize a module path to a filesystem path.
onUpdateFinish(callback): voidQueue a callback after an update finishes.
outputPath(): stringReturn the resolved output directory.
addExtraWatchFile(root: string, paths: string[]): voidAdd extra watch files.
stats(): unknownReturn native compiler stats.
waitForCompileFinish(): Promise<void>Wait for an in-progress compile to finish.
invalidateModule(moduleId: string): voidInvalidate one module in the native compiler.
writeMetadata(name, data, options?): voidStore JSON-serialized metadata for plugins/APIs.
readMetadata(name, options?): unknownRead metadata written with writeMetadata.
readMetadataByScope(scope: string): unknown[]Read metadata entries by scope.

createInlineCompiler

ts
createInlineCompiler(
  config: ResolvedUserConfig,
  options?: ResolvedCompilation
): Compiler

Creates a compiler by overriding the resolved compilation object inline.

100%

Drag or pinch to explore. Keyboard: + / − zoom, arrows pan, 0 resets, Esc closes.