---
title: "JavaScript API"
locale: "en"
version: "current"
canonicalUrl: "https://farmfe.org/docs/api/javascript-api"
publicationStatus: "prerelease"
---

<a id="javascript-api"></a>
# 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**

```sh
npm add @farmfe/core@latest
```

**pnpm**

```sh
pnpm add @farmfe/core@latest
```

**yarn**

```sh
yarn add @farmfe/core@latest
```

**bun**

```sh
bun add @farmfe/core@latest
```


<a id="top-level-helpers"></a>
## Top-level helpers


<a id="start"></a>
### ` 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()]
});
```


<a id="build"></a>
### ` 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' }
  }
});
```


<a id="watch"></a>
### ` 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' } } });
```


<a id="preview"></a>
### ` 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' }
  }
});
```


<a id="clean"></a>
### ` 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());
```


<a id="config-and-environment-helpers"></a>
## Config and environment helpers


<a id="defineconfig"></a>
### ` defineConfig `


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

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


<a id="resolveconfig"></a>
### ` 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);
```


<a id="loadenv"></a>
### ` 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());
```


<a id="dev-server-apis"></a>
## Dev server APIs


<a id="servercreateserver"></a>
### ` 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();
```


<a id="server-instance-methods"></a>
### ` 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() `. |


<a id="previewserver"></a>
### ` 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.


<a id="compiler-apis"></a>
## 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();
```


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


<a id="createinlinecompiler"></a>
### ` createInlineCompiler `


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


Creates a compiler by overriding the resolved ` compilation ` object inline.
