Import JSON files

Rslib supports importing JSON files in code, and also supports importing YAML and TOML files and converting them to JSON format.

JSON file

You can directly import JSON files in JavaScript files.

WARNING

In bundle mode, JSON files support both default and named import.

In bundleless mode, JSON files only support named import.

Default import

example.json
{
  "name": "foo",
  "items": [1, 2]
}
index.js
import example from './example.json';

console.log(example.name); // 'foo';
console.log(example.items); // [1, 2];

Named import

Rslib also supports importing JSON files through named import.

Here is an example, assuming the source code is as follows:

src/index.ts
src/example.json
import { name } from './example.json';

console.log(name); // 'foo';

Based on the configuration in the output structure specified in the configuration file, the following outputs will be emitted:

bundle
bundleless
dist/index.js
var example_namespaceObject = {
  u: 'foo',
};
console.log(example_namespaceObject.u);

YAML file

YAML is a data serialization language commonly used for writing configuration files.

By adding the @rsbuild/plugin-yaml plugin, you can import .yaml or .yml files in JavaScript and they will be automatically converted to JavaScript objects.

npm
yarn
pnpm
bun
npm add @rsbuild/plugin-yaml -D

Register plugin

You can register the plugin in the rslib.config.ts file:

rslib.config.ts
import { pluginYaml } from '@rsbuild/plugin-yaml';

export default {
  plugins: [pluginYaml()],
};

Example

src/index.ts
src/example.yaml
import { name } from './example.yaml';

console.log(name); // 'foo';

TOML file

TOML is a semantically explicit, easy-to-read configuration file format.

By adding the @rsbuild/plugin-toml plugin, you can import .toml files in JavaScript and it will be automatically converted to JavaScript objects.

npm
yarn
pnpm
bun
npm add @rsbuild/plugin-toml -D

Register plugin

You can register the plugin in the rslib.config.ts file:

rslib.config.ts
import { pluginToml } from '@rsbuild/plugin-toml';

export default {
  plugins: [pluginToml()],
};

Example

src/index.ts
src/example.toml
import { name } from './example.toml';

console.log(name); // 'foo';

Type declaration

When you import YAML or Toml files in TypeScript code, please create a src/env.d.ts file in your project and add the corresponding type declarations.

  • Method 1: If the @rslib/core package is installed, you can reference the preset types provided by @rslib/core:
src/env.d.ts
/// <reference types="@rslib/core/types" />
  • Method 2: Manually add the required type declarations:
src/env.d.ts
declare module '*.yaml' {
  const content: Record<string, any>;
  export default content;
}
declare module '*.yml' {
  const content: Record<string, any>;
  export default content;
}
declare module '*.toml' {
  const content: Record<string, any>;
  export default content;
}