引用 JSON 文件

Rslib 支持在代码中引用 JSON 文件,也支持引用 YAMLTOML 文件并将其转换为 JSON 格式。

JSON 文件

你可以直接在 JavaScript 文件中引用 JSON 文件。

WARNING

在 bundle 模式下,JSON 文件支持默认引用和具名引用。

在 bundleless 模式下,JSON 文件仅支持具名引用。

默认引用

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];

具名引用

Rslib 同样支持通过 named import 来引用 JSON 文件。

下面是一个使用示例,假设源码如下:

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

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

会根据配置文件中的 产物结构 配置,输出如下产物:

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

YAML 文件

YAML 是一种数据序列化语言,通常用于编写配置文件。

通过添加 @rsbuild/plugin-yaml 插件,你可以在 JavaScript 中引用 .yaml.yml 文件,它们会被自动转换为 JavaScript 对象。

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

注册插件

你可以在 rslib.config.ts 文件中注册插件:

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

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

示例

src/index.ts
src/example.yaml
import example from './example.yaml';

console.log(example.hello); // 'world';
console.log(example.foo); // { bar: 'baz' };

TOML 文件

TOML 是一种语义明显、易于阅读的配置文件格式。

通过添加 @rsbuild/plugin-toml 插件,你可以在 JavaScript 中引用 .toml 文件,它们会被自动转换为 JavaScript 对象。

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

注册插件

你可以在 rslib.config.ts 文件中注册插件:

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

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

示例

src/index.ts
src/example.toml
import example from './example.toml';

console.log(example.hello); // 'world';
console.log(example.foo); // { bar: 'baz' };

类型声明

当你在 TypeScript 代码中引用 YAML 或 TOML 文件时,请在项目中创建 src/env.d.ts 文件,并添加相应的类型声明。

  • 方法一:如果项目里安装了 @rslib/core 包,你可以直接引用 @rslib/core 提供的 预设类型
src/env.d.ts
/// <reference types="@rslib/core/types" />
  • 方法二:手动添加需要的类型声明:
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;
}