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

<a id="javascript-api"></a>
# JavaScript API


Farm 从 ` @farmfe/core ` 暴露 Node.js API，用于开发服务器、生产构建、watch 模式、预览服务器、配置加载、环境变量加载和直接访问编译器。


**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="顶层辅助方法"></a>
## 顶层辅助方法


<a id="start"></a>
### ` start `


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


启动 Farm 开发服务器。它会以 ` dev ` / ` development ` 模式解析配置、创建服务器、开始监听、编译项目并打印服务器 URL。


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


以 ` build ` / ` production ` 模式解析配置，创建编译器，执行一次编译并将资源写入磁盘。


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


以 watch 模式构建，并在监听文件变化时重新构建。如果启用了懒编译，Farm 也会启动懒编译服务器。


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

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


<a id="preview"></a>
### ` preview `


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


为已有的生产构建产物启动预览服务器。


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


清理解析后项目的 Farm 持久化缓存文件。传入 ` recursive: true ` 可递归查找嵌套的 ` node_modules ` 目录。


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

await clean(process.cwd());
```


<a id="配置和环境辅助方法"></a>
## 配置和环境辅助方法


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


在调用 ` createCompiler ` 等底层 API 前，先使用 ` resolveConfig ` 解析配置。


```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[]]
```


从 ` envDir ` 加载 ` .env `、` .env.local `、` .env.${mode} ` 和 ` .env.${mode}.local `。前缀默认是 ` ['FARM_', 'VITE_'] `。


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

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


<a id="开发服务器-api"></a>
## 开发服务器 API


<a id="servercreateserver"></a>
### ` Server.createServer `


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


创建并初始化开发服务器。调用 ` listen() ` 开始监听 HTTP 服务并执行初始编译。


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

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


<a id="server-实例方法"></a>
### ` Server ` 实例方法


| 方法 | 描述 |
| --- | --- |
| ` listen(): Promise<void> ` | 开始监听、编译并设置 watch 行为。 |
| ` restart(): Promise<Server> ` | 关闭当前服务器，并使用相同 inline config 创建替代服务器。 |
| ` restartServer(): Promise<void> ` | 重启并在 host/port 变化时打印 URL。 |
| ` getCompiler(): Compiler \| undefined ` | 在服务器开始编译后返回当前编译器。 |
| ` setCompiler(compiler: Compiler): void ` | 替换服务器编译器实例。 |
| ` addWatchFile(root: string, deps: string[]): void ` | 通过编译器添加额外监听文件。 |
| ` close(): Promise<void> ` | 关闭 watcher、WebSocket 服务器和 HTTP 服务器。 |
| ` printUrls(): void ` | 在 ` listen() ` 后打印解析出的服务器 URL。 |


<a id="previewserver"></a>
### ` PreviewServer `


` preview() ` 是预览模式的高层 API。需要更底层控制时，` PreviewServer ` 可通过 ` @farmfe/core ` 的 server 模块导出使用。


<a id="编译器-api"></a>
## 编译器 API


从解析后的配置创建编译器：


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

const config = await resolveConfig({}, 'build', 'production');
const compiler = createCompiler(config);
await compiler.compile();
```


| 方法 | 描述 |
| --- | --- |
| ` compile(): Promise<void> ` | 执行一次编译。设置 ` FARM_PROFILE ` 时内部使用同步编译。 |
| ` compileSync(): void ` | 同步执行编译。 |
| ` update(paths, sync?, ignoreCompilingCheck?, generateUpdateResource?): Promise<JsUpdateResult> ` | 增量更新模块。` paths ` 是 ` { path, type } ` 列表，type 为 ` added `、` updated ` 或 ` removed `。 |
| ` traceDependencies(): Promise<unknown> ` | 从原生编译器返回配置/模块依赖追踪信息。 |
| ` traceModuleGraph(): Promise<TracedModuleGraph> ` | 返回追踪后的模块图。 |
| ` hasModule(resolvedPath: string): boolean ` | 检查解析路径是否在模块图中。 |
| ` getParentFiles(idOrResolvedPath: string): string[] ` | 返回某模块的父模块/导入方。 |
| ` resources(): Record<string, Buffer> ` | 返回按资源名索引的编译资源 buffer。 |
| ` resource(path: string): Buffer ` | 返回单个编译资源 buffer。 |
| ` resourcesMap(): Record<string, Resource> ` | 返回按资源名索引的完整资源元数据。 |
| ` writeResourcesToDisk(): void ` | 写入资源并运行 ` writeResources ` 插件 hook。 |
| ` callWriteResourcesHook(): void ` | 不写入资源，仅运行 JS 插件 ` writeResources ` hook。开发模式下 ` server.writeToDisk ` 禁用时会使用它。 |
| ` removeOutputPathDir(): void ` | 删除配置的输出目录。 |
| ` resolvedWatchPaths(): string[] ` | 返回编译器监听的模块路径。 |
| ` resolvedModulePaths(root: string): string[] ` | 返回 ` root ` 下解析出的模块路径。 |
| ` transformModulePath(root: string, path: string): string ` | 将模块路径规范化为文件系统路径。 |
| ` onUpdateFinish(callback): void ` | 在更新完成后排队执行回调。 |
| ` outputPath(): string ` | 返回解析后的输出目录。 |
| ` addExtraWatchFile(root: string, paths: string[]): void ` | 添加额外监听文件。 |
| ` stats(): unknown ` | 返回原生编译器 stats。 |
| ` waitForCompileFinish(): Promise<void> ` | 等待正在进行的编译结束。 |
| ` invalidateModule(moduleId: string): void ` | 使原生编译器中的一个模块失效。 |
| ` writeMetadata(name, data, options?): void ` | 为插件/API 写入 JSON 序列化后的元数据。 |
| ` readMetadata(name, options?): unknown ` | 读取 ` writeMetadata ` 写入的元数据。 |
| ` readMetadataByScope(scope: string): unknown[] ` | 按 scope 读取元数据条目。 |


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


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


通过内联覆盖解析后配置中的 ` compilation ` 对象来创建编译器。
