---
title: "JavaScript Api"
locale: "zh"
version: "1.x"
canonicalUrl: "https://farmfe.org/zh/docs/1.x/api/javascript-api"
publicationStatus: "prerelease"
---

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


` Farm ` 提供完整的开发服务器、编译器、监听器等 ` JavaScript Api `, 开发者可以通过引入 ` @farmfe/core ` 包来使用这些 Api。


安装 ` @farmfe/core ` 包:


**npm**

```javascript
npm install @farmfe/core@latest
```


**yarn**

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


**pnpm**

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



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


` Start ` 方法用于快速启动开发服务器


调用 ` start ` 方法之后就可以在当前控制台看见可用的 ` ip ` 地址的日志信息, 默认会编译当前目录下的 ` index.html ` 文件


类型:


```typescript
start(options: InlineConfig): Promise<void>
```


基本示例:


```javascript
import { start, logger } from "@farmfe/core";
try {
  await start(options);
} catch (error) {
  logger.error(`Failed to start server:\n ${error.stack}`);
  process.exit(1);
}
```


<a id="build"></a>
## Build


` Build ` 方法对生产环境进行构建


调用 ` build ` 方法之后默认构建浏览器产物, 并且会在当前目录下生成一个 ` dist ` 文件夹, 如若需要构建不同环境以及不同版本产物, 例如 ` node `、` node-next `、` browser `、` browser-es2017 ` 等, 可以通过查看 [output targetEnv](</docs/config/compilation-options#output>) 来进行配置.
类型:


```typescript
build(options: InlineConfig): Promise<void>
```


基本示例:


```javascript
import { build, logger } from "@farmfe/core";
try {
  await build(options);
} catch (error) {
  logger.error(`error during build:\n ${error.stack}`);
  process.exit(1);
}
```


<a id="watch"></a>
## Watch


` Watch ` 方法对当前项目的编译进行实时更新, 等同于 ` npx farm build --watch `, 一般作用于 ` node ` 环境


类型:


```typescript
watch(options: InlineConfig): Promise<void>
```


基本示例:


```javascript
import { watch, logger } from "@farmfe/core";
try {
  await watch(defaultOptions);
} catch (error) {
  logger.error(`error during watch project:\n ${error.stack}`);
  process.exit(1);
}
```


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


` Preview ` 方法启动一个预览服务器, 对生产环境产物进行预览, 使用时需要确保已经通过 ` build ` 方法进行构建, 并且生成了正确的生产环境产物


类型:


```typescript
preview(options: InlineConfig): Promise<void>
```


基本示例:


```javascript
import { preview, logger } from "@farmfe/core";
try {
  await preview(defaultOptions);
} catch (error) {
  logger.error(`Failed to start preview server:\n ${error.stack}`);
  process.exit(1);
}
```


<a id="clean"></a>
## Clean


` Clean ` 方法清理 ` farm ` 增量构建所产生缓存, 如果您开启了增量构建功能, 那么这个方法可能对您有所帮助



> [!WARNING]
> 注意
> 
> 对于目前使用增量构建功能而导致某些不可预知或者未发现的问题所导致的程序崩溃, 可以尝试通过清理缓存来解决问题, 若并不能解决请在 github 上提交 issues



类型:


```typescript
clean(options: InlineConfig): Promise<void>
```


基本示例:


```javascript
import { clean, logger } from "@farmfe/core";
try {
  await clean(defaultOptions);
} catch (error) {
  logger.error(`Failed to clean cache:\n ${error.stack}`);
  process.exit(1);
}
```


<a id="loadenv"></a>
## loadEnv


从 .env 文件加载环境变量。


```ts
type LoadEnvFunc = (
  mode: string,
  envDir: string,
  prefixes: string | string[] = ['FARM_', 'VITE_']
) => [env: Record<string, string>, existsEnvFiles: string[]];
```


- ` mode ` 是 ` development `、` Production ` 或任何字符串。 ` loadEnv ` 将尝试加载 ``` [``.env``, ``.env.local``, ``.env.${mode}``, ``.env.${mode}.local``]  ``` 为 ` envDir `。
- ` envDir ` 是 ` .env ` 文件所在的目录。
- ` prefixes ` 是环境变量的前缀。 默认值为 ` ['FARM_', 'VITE_'] ` 。 带有这些前缀的环境变量将自动注入到` define `中。


```js
const [env, files] = loadEnv('development', '/path/to/project/env');
// use env
```


<a id="createdevserver"></a>
### createDevServer


` createDevServer ` 方法用于启动本地开发服务器, 需要先实例化 ` Server ` 对象, 传递参数需要 ` farm ` 的 ` compiler `


类型:


```typescript
createDevServer(options: DevServerOptions): Promise<void>
```


基本示例:


```javascript
import { Server } from "@farmfe/core";
const server = new Server();
await server.createDevServer(options);
server.listen()
```


<a id="createpreviewserver"></a>
### createPreviewServer


创建一个 预览服务器，用于预览生产环境产物


类型:


```typescript
createPreviewServer(options: DevServerOptions): Promise<void>
```


基本示例:


```javascript
import { Server } from "@farmfe/core";
const server = new Server();
await server.createPreviewServer(options);
```


<a id="getcompiler"></a>
### getCompiler


获取当前开发服务器的编译器实例, 在实例化 ` Server ` 的时候需要传递一个 ` compiler ` 参数


类型:


```typescript
getCompiler(): Compiler
```


基本示例:


```javascript
import { Server, Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const server = new Server({
  compiler
});
const compiler = server.getCompiler();
```


<a id="close"></a>
### close


关闭当前由 ` createDevServer ` 开启的所有 ` Server ` 以及 ` Webscoker ` 服务


基本示例:


```javascript
import { Server } from "@farmfe/core";
const server = new Server();
await server.createDevServer(options);
server.listen()
await server.close();
```


<a id="compiler"></a>
## Compiler


` Compiler ` 提供一系列编译器的 ` Api `,可以通过实例化 ` Compiler ` 创建一个编译器实例。


基本示例


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile();
```


<a id="compile"></a>
### compile


编译器异步启动编译过程。返回一个 ` promise `



> [!NOTE]
> 备注
> 
> 如果设置了特定的环境变量 (procee.env.FARM\_PROFILE) , 则执行同步编译。



类型:


```typescript
compile(): promise<void>
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile();
```


<a id="compilesync"></a>
### compileSync


编译器同步启动编译过程。


类型:


```typescript
compileSync(): void
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
compiler.compileSync();
```


<a id="tracedependencies"></a>
### traceDependencies


追踪文件之间的依赖关系, 根据 ` compiler ` 传递的 ` config ` 参数中的 ` input ` 返回当前文件的所有依赖关系, 这对于根据文件依赖关系进行重启编译非常有用。


类型:


```typescript
traceDependencies(): Array[string]
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";

const config = {
  input: "./farm.config.js"
}
const compiler = new Compiler(config);
const dependencies = compiler.traceDependencies();
```


返回一个所有依赖关系的路径组成的数组


<a id="update"></a>
### update


根据提供的路径来更新编译, 返回一个解析为 ` JsUpdateResult ` 的 ` Promise `。如果编译已经在进行中, 它会等待处理并更新。如果设置了 ` ignoreCompilingCheck ` 为 ` true `, 则不会检查编译状态。


类型:


```typescript
update(paths: Array<string>, sync: boolean, ignoreCompilingCheck: boolean): JsUpdateResult
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = await compiler.update(paths, true, true);
```


<a id="hasmodule"></a>
### hasModule


传递一个 ` path ` 判断当前 ` path ` 是否处于 ` compiler ` 所编译的模块中。


类型:


```typescript
hasModule(path: string): boolean
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = compiler.hasModule(path);
```


<a id="getparentfiles"></a>
### getParentFiles


检索由 模块导入名 (` id `) 或已解析路径标识(` resolvedPath `)的模块导入的当前文件。


类型:


```typescript
getParentFiles(resolvedPath: string): Array<string>
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = compiler.getParentFiles(resolvedPath);
```


<a id="resources"></a>
### resources


返回所有经过 ` compiler ` 编译后的所有产物资源


类型:


```typescript
type Resource = {
  path: string
  buffer: Buffer
}
resources(): Array<Resource>
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
const result = compiler.resources();
```


<a id="resource"></a>
### Resource


根据传入的文件返回当前产物的 ` buffer `


类型:


```typescript
resource(path: string): Buffer | null
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
const result = compiler.resource(path);
```


<a id="writeresourcestodisk"></a>
### writeResourcesToDisk


根据配置输出路径将资源写入磁盘


类型:


```typescript
writeResourcesToDisk(): void
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
compiler.writeResourcesToDisk();
```


<a id="removeoutputpathdir"></a>
### removeOutputPathDir


删除输出产物路径目录


类型:


```typescript
removeOutputPathDir(): void
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
compiler.removeOutputPathDir();
```


<a id="resolvedwatchpaths"></a>
### resolvedWatchPaths


返回已解析的监视路径


类型:


```typescript
resolvedWatchPaths(): Array<string>
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
const result = compiler.resolvedWatchPaths();
```


<a id="resolvedmodulepaths"></a>
### resolvedModulePaths


返回相对于提供的根路径已解析的模块路径。


类型:


```typescript
resolvedModulePaths(rootPath: string): Array<string>
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
const result = compiler.resolvedModulePaths(rootPath);
```


<a id="onupdatefinish"></a>
### onUpdateFinish


添加一个在更新过程完成后执行的回调。


类型:


```typescript
onUpdateFinish(callback: (...args: any[]) => any): void
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
compiler.onUpdateFinish(callback);
```


<a id="outputpath"></a>
### outputPath


返回已解析的输出路径


类型:


```typescript
outputPath(): string
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = compiler.outputPath();
```


<a id="addextrawatchfile"></a>
### addExtraWatchFile


为编译器添加额外的监视文件。


类型:


```typescript
addExtraWatchFile(rootPath: string,. filePath: string[]): void
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
compiler.addExtraWatchFile(rootPath, filePath);
```


<a id="modules"></a>
### modules


返回文件模块解析后的对象数组


类型:


```typescript
export interface Module {
  id: string
  moduleType: string
  moduleGroups: Array<string>
  resourcePot?: string
  sideEffects: boolean
  sourceMapChain: Array<string>
  external: boolean
  immutable: boolean
}
modules(): Array<Module>
```


基本示例:


```javascript
import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = compiler.modules();
```
