> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Rslib core

This chapter introduces some of the core methods provided by Rslib.

## createRslib

Create an [Rslib instance](/api/javascript-api/instance.md).

- **Type:**

```ts
function createRslib(options?: CreateRslibOptions): Promise<RslibInstance>;
```

- **Example:**

```ts
import { createRslib } from '@rslib/core';

const rslib = await createRslib({
  config: {
    // Rslib configuration
  },
});
```

### Options

The first parameter of `createRslib` is an `options` object with the following properties:

```ts
type CreateRslibOptions = {
  cwd?: string;
  config?:
    | RslibConfig
    | LoadConfigResult
    | (() => Promise<RslibConfig | LoadConfigResult>);
  loadEnv?: boolean | LoadEnvOptions;
};
```

- `cwd`: The root path of the current build, defaults to `process.cwd()`.
- `config`: Rslib configuration object or the complete result returned by [loadConfig](#loadconfig). Refer to [Configuration overview](/config/index.md) for all available configuration options.
- `loadEnv`: Whether to call the [loadEnv](/api/javascript-api/core.md#loadenv) method to load environment variables and define them as global variables via [source.define](/config/rsbuild/source.md#sourcedefine).

Pass the complete `loadConfig` result to preserve configuration file paths and imported dependencies for file watching and persistent cache invalidation. Passing only `result.content` does not preserve this metadata.

### Load configuration async

`config` can also be an async function for dynamically loading Rslib configuration and performing custom operations.

```ts
import { createRslib, loadConfig } from '@rslib/core';

const rslib = await createRslib({
  config: async () => {
    const result = await loadConfig();
    someFunctionToUpdateConfig(result.content);
    return result;
  },
});
```

### Load environment variables

The `loadEnv` option in `createRslib` calls the [loadEnv](/api/javascript-api/core.md#loadenv) method to load environment variables:

```ts
const rslib = await createRslib({
  loadEnv: true,
});
```

Setting `loadEnv: true` automatically completes these steps:

1. Call the `loadEnv` method to load environment variables.
2. Add [source.define](/config/rsbuild/source.md#sourcedefine) configuration, defining the `publicVars` returned by `loadEnv` as global variables.
3. Watch the `.env` file for changes, restart build or restart the dev server when the file changes, and invalidate the build cache.
4. Automatically call the `cleanup` method returned by `loadEnv` when closing the build or dev server.

You can also pass in the options of the [loadEnv](/api/javascript-api/core.md#loadenv) method, for example:

```ts
const rslib = await createRslib({
  loadEnv: {
    prefixes: ['PUBLIC_', 'REACT_COMPS_'],
  },
});
```

## loadConfig

Load Rslib configuration file.

- **Type:**

```ts
function loadConfig(params?: {
  // Default is process.cwd()
  cwd?: string;
  // Specify the configuration file (relative or absolute path)
  path?: string;
  // Config file names to search when path is not specified
  configFileNames?: string[];
  meta?: Record<string, unknown>;
  envMode?: string;
  /**
   * The command passed to the config function.
   * @default process.argv[2]
   */
  command?: string;
  /**
   * Specify the config loader, can be `auto`, `jiti` or `native`.
   * - 'auto': Use native Node.js loader first, fallback to jiti if failed
   * - 'jiti': Use jiti as loader, which supports TypeScript and ESM out of the box
   * - 'native': Use native Node.js loader. TypeScript config files require
   *   native TypeScript support, such as Node.js 22.6+.
   * @default 'auto'
   */
  loader?: 'auto' | 'jiti' | 'native';
  /**
   * The export name to read from the config file.
   * Set to `false` to execute the config file without reading exports.
   * @default 'default'
   */
  exportName?: string | false;
}): Promise<{
  content: RslibConfig;
  filePath: string | null;
  dependencies: string[];
}>;
```

- **Example:**

```ts
import { createRslib, loadConfig } from '@rslib/core';

// load `rslib.config.*` file by default
const result = await loadConfig();

console.log(result.content); // -> Rslib config object

const rslib = await createRslib({
  config: result,
});
```

If the Rslib config file does not exist in the cwd directory, the return value of the loadConfig method is `{ content: {}, filePath: null, dependencies: [] }`.

When `path` is not specified, `loadConfig` searches for config files in the following order:

- `rslib.config.mjs`
- `rslib.config.ts`
- `rslib.config.js`
- `rslib.config.cjs`
- `rslib.config.mts`
- `rslib.config.cts`

If multiple config files exist at the same time, `loadConfig` uses the first matching file in this list.

Most `loadConfig` options follow the same usage as Rsbuild. In Rslib, the default lookup list uses `rslib.config.*`, and the returned `content` is typed as [RslibConfig](/api/javascript-api/types.md#rslibconfig); see [loadConfig -- Rsbuild](https://rsbuild.rs/api/javascript-api/core#loadconfig) for more usage details.

## loadEnv

Load the [.env](https://rsbuild.rs/guide/advanced/env-vars#env-file) file and return all environment variables starting with the specified prefixes.

The usage is the same as Rsbuild, see [loadEnv -- Rsbuild](https://rsbuild.rs/api/javascript-api/core#loadenv) for details.

:::tip

- Rslib CLI will automatically call the `loadEnv()` method. If you are using the Rslib CLI, you can set the `mode` parameter through the `--env-mode` option.
- The `loadEnv` option in [createRslib](#createrslib) will help you call the `loadEnv()` method and handle related operations.

:::

## mergeRslibConfig

Used to merge multiple Rslib configuration objects.

The `mergeRslibConfig` function takes multiple configuration objects as parameters. It deep merges each configuration object, automatically combining multiple function values into an array of sequentially executed functions, and returns a merged configuration object.

- **Type:**

```ts
function mergeRslibConfig(...configs: (RslibConfig | undefined)[]): RslibConfig;
```

### Basic example

```ts
import { mergeRslibConfig } from '@rslib/core';

const config1 = {
  lib: [
    {
      format: 'esm',
    },
  ],
  output: {
    target: 'node',
  },
};
const config2 = {
  output: {
    target: 'web',
  },
};

const mergedConfig = mergeRslibConfig(config1, config2);

console.log(mergedConfig);
// {
//   lib: [
//     {
//       format: 'esm',
//     },
//   ],
//   output: {
//     target: 'web',
//   },
// }
```

### Merge rules

For each item in the [lib](/config/lib.md) object array, the merge is processed based on the [id](/config/lib/id.md) field:

- Objects with the same `id` are deeply merged
- Objects without `id` will be appended to the end of the result array
- Objects with `id` are sorted in order of first occurrence

Other configuration fields follow the same merge rules as [mergeRsbuildConfig](https://rsbuild.rs/api/javascript-api/core#merge-rules).

```ts
import { mergeRslibConfig } from '@rslib/core';

const config1: RslibConfig = {
  lib: [
    {
      format: 'iife',
    },
    {
      id: 'esm',
      format: 'esm',
      syntax: 'es2020',
      resolve: {
        alias: {
          A: 'a',
        },
      },
      output: {
        externals: ['pkg1'],
      },
    },
    {
      id: 'cjs',
      format: 'cjs',
    },
  ],
};

const config2: RslibConfig = {
  lib: [
    {
      id: 'esm',
      syntax: 'es2021',
      output: {
        externals: ['pkg2'],
      },
      resolve: {
        alias: {
          B: 'b',
        },
      },
    },
    {
      format: 'umd',
    },
  ],
};

const mergedConfig = mergeRslibConfig(config1, config2);

console.log(mergedConfig);
// {
//   lib: [
//     {
//       format: 'esm',
//       id: 'esm',
//       output: {
//         externals: ['pkg1', 'pkg2'],
//       },
//       resolve: {
//         alias: {
//           A: 'a',
//           B: 'b',
//         },
//       },
//       syntax: 'es2021',
//     },
//     {
//       format: 'cjs',
//       id: 'cjs',
//     },
//     {
//       format: 'iife',
//     },
//     {
//       format: 'umd',
//     },
//   ],
// }
```

## rspack

If you need to access the API or plugins exported by [@rspack/core](https://npmjs.com/package/@rspack/core), you can directly import the `rspack` object from `@rslib/core` without installing the `@rspack/core` package separately.

- **Type:** `Rspack`
- **Example:**

```ts
// the same as `import { rspack } from '@rspack/core'`
import { rspack } from '@rslib/core';

console.log(rspack.rspackVersion); // a.b.c
console.log(rspack.util.createHash);
console.log(rspack.BannerPlugin);
```

:::tip

- Refer to [Rspack plugins](https://rspack.rs/plugins/) and [Rspack JavaScript API](https://rspack.rs/api/javascript-api/) to learn more about the available Rspack APIs.
- It's not recommended to manually install the `@rspack/core` package, as it may conflict with the version that Rslib depends on.

:::

## rsbuild

If you need to access the API exported by [@rsbuild/core](https://npmjs.com/package/@rsbuild/core), you can directly import the `rsbuild` object from `@rslib/core` without installing the `@rsbuild/core` package separately.

- **Example:**

```ts
import { rsbuild } from '@rslib/core';

console.log(rsbuild.version);
```

:::tip

Refer to [Rsbuild core](https://rsbuild.rs/api/javascript-api/core) for available Rsbuild APIs.

:::

## version

The version of `@rslib/core` currently in use.

- **Type:** `string`
- **Example:**

```ts
import { version } from '@rslib/core';

console.log(version); // 1.0.0
```
