Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(assets): add assets, json, svgr usage document #741

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion tests/integration/asset/__snapshots__/index.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@ export { draft_rslib_entry_namespaceObject as default };
`;

exports[`use json 1`] = `
"JSON.parse('{"foo":1,"bar":["2"]}');
"var data_namespaceObject = {
R: 1,
K: [
"2"
]
};
console.log(data_namespaceObject.R);
console.log(data_namespaceObject.K);
"
`;

Expand Down
5 changes: 3 additions & 2 deletions tests/integration/asset/json/src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import a from './assets/data.json';
import { bar, foo } from './assets/data.json';

a;
console.log(foo);
console.log(bar);
2 changes: 1 addition & 1 deletion website/docs/en/config/lib/bundle.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ export default defineConfig({
});
```

When `bundle` is set to `false`, as known as bundleless mode, Rslib will only transform the code into multiple files.
When `bundle` is set to `false`, as known as bundleless mode, Rslib will transform the code into multiple files.

```diff
.
Expand Down
4 changes: 3 additions & 1 deletion website/docs/en/guide/basic/output-structure.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ A bundle is a package of build artifacts, which may be a single file or multiple

bundleless, on the other hand, means that each source file is compiled and built separately, but not bundled together. Each output file can be found with its corresponding source code file. The process of bundleless build can also be understood as the process of code conversion of source files only.

![rslib-bundleless-mode](https://assets.rspack.dev/rslib/rslib-bundleless-mode.png)

They have their own benefits.

- bundle can reduce the size of build artifacts and also pre-package dependencies to reduce the size of installed dependencies. Packaging libraries in advance can speed up application project builds.
- bundle can reduce the size of build artifacts and also prebundle dependencies to reduce the size of installed dependencies and increase security. Packaging libraries in advance can speed up application project builds.
- bundleless maintains the original file structure and is more conducive to debugging and tree shaking.

:::warning
Expand Down
4 changes: 2 additions & 2 deletions website/docs/zh/config/lib/bundle.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
- **类型:** `boolean`
- **默认值:** `undefined`

指定是否打包库,当 `bundle` 设置为 `true` 时称为 bundle 模式,设置为 `false` 时称为 bundleless 模式。更多详情请参见 [bundle / bundleless](/guide/basic/output-structure#bundle--bundleless)。
指定是否打包库,当 `bundle` 设置为 `true` 时称为 bundle 模式,设置为 `false` 时称为 bundleless 模式。更多详情请参考 [bundle / bundleless](/guide/basic/output-structure#bundle--bundleless)。

## 设置入口

Expand Down Expand Up @@ -128,7 +128,7 @@ export default defineConfig({
});
```

当 `bundle` 设置为 `false` 时,也称为 bundleless 模式,Rslib 只会将代码转换为多个文件
当 `bundle` 设置为 `false` 时,也称为 bundleless 模式,Rslib 会将代码转换为多个文件

```diff
.
Expand Down
2 changes: 1 addition & 1 deletion website/docs/zh/config/lib/syntax.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Syntax = EcmaScriptVersion | string[];

配置 JavaScript 和 CSS 将被降级的语法版本。

参见 [产物兼容性 - 语法降级](/guide/advanced/output-compatibility) 了解更多详情。
参考 [产物兼容性 - 语法降级](/guide/advanced/output-compatibility) 了解更多详情。

## 设置 ECMAScript 版本

Expand Down
8 changes: 8 additions & 0 deletions website/docs/zh/config/rsbuild/output.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import { RsbuildDocBadge } from '@components/RsbuildDocBadge';

与构建产物相关的选项。

## output.assetPrefix <RsbuildDocBadge path="/config/output/asset-prefix" text="output.charset" />

使用该选项设置静态资源的 URL 前缀,比如设置为 CDN 地址。

在 [format](/config/lib/format) 为 `cjs` 或 `esm` 时,Rslib 默认会将 `output.assetPrefix` 设置为 `"auto"`。

## output.charset <RsbuildDocBadge path="/config/output/charset" text="output.charset" />

指定输出文件的 [字符编码](https://developer.mozilla.org/en-US/docs/Glossary/Character_encoding),以确保它们在不同的环境中能够正确显示。
Expand All @@ -24,6 +30,8 @@ import { RsbuildDocBadge } from '@components/RsbuildDocBadge';

设置图片、字体、媒体等静态资源被自动内联为 base64 的体积阈值。

在 [format](/config/lib/format) 为 `cjs` 或 `esm` 时,Rslib 默认会将 `output.dataUriLimit` 设置为 `0`,不内联任何静态资源,以便于应用侧的构建工具处理和优化。

## output.distPath <RsbuildDocBadge path="/config/output/dist-path" text="output.distPath" />

设置构建产物的输出目录,Rsbuild 会根据产物的类型输出到对应的子目录下。
Expand Down
3 changes: 3 additions & 0 deletions website/docs/zh/guide/advanced/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
"third-party-deps",
"output-compatibility",
"dts",
"static-assets",
"svgr-files",
"json-files",
"module-federation",
"storybook"
]
39 changes: 39 additions & 0 deletions website/docs/zh/guide/advanced/json-files.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# 引用 JSON 文件

Rslib 支持在代码中引用 JSON 文件。

## JSON 文件

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

### 示例

```json title="example.json"
{
"name": "foo",
"items": [1, 2]
}
```

```js title="index.js"
import example from './example.json';

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

### 具名引用

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

```js
import { name } from './example.json';

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

:::warning

Bundleless 下,JSON 文件仅支持具名引用。

:::
204 changes: 204 additions & 0 deletions website/docs/zh/guide/advanced/static-assets.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# 引用静态资源

Rslib 支持在代码中引用图片、字体、音频、视频等类型的静态资源。

## 静态资源格式

以下是 Rslib 默认支持的静态资源格式:

- **图片**:png、jpg、jpeg、gif、svg、bmp、webp、ico、apng、avif、tif、tiff、jfif、pjpeg、pjp、cur。
- **字体**:woff、woff2、eot、ttf、otf、ttc。
- **音频**:mp3、wav、flac、aac、m4a、opus。
- **视频**:mp4、webm、ogg、mov。

如果你需要引用其他格式的静态资源,请参考 [扩展静态资源类型](#扩展静态资源类型)。

## 在 JS 文件中引用

在 JS 文件中,可以直接通过 `import` 的方式引用相对路径下的静态资源:

```tsx
// 引用 src/assets 目录下的 logo.png 图片
import logo from './assets/logo.png';

console.log(logo); // "/static/logo.[hash].png"

export default = () => <img src={logo} />;
```

也可以使用**路径别名**来引用:

```tsx
import logo from '@/assets/logo.png';

console.log(logo); // "/static/logo.[hash].png"

export default = () => <img src={logo} />;
```

在 [format](/config/lib/format) 为 `cjs` 或 `esm` 时,Rslib 会将产物视为需要被其他打包工具再次消费的中间产物,会将源文件转化为一个 JS 文件和一个根据 [output.distPath](/config/rsbuild/output#outputdistpath) 输出的静态资源文件,用于保留对静态资源的 `import` 语句。

import { Tabs, Tab } from '@theme';

<Tabs>
<Tab label="dist/index.mjs">

```tsx
import logo from './assets/logo.mjs';

console.log(logo);
```

</Tab>
<Tab label="dist/assets/logo.mjs">

```tsx
import logo_rslib_entry_namespaceObject from '../static/svg/logo.svg';
export { logo_rslib_entry_namespaceObject as default };
```

</Tab>
</Tabs>

## 在 CSS 文件中引用

在 CSS 文件中,可以引用相对路径下的静态资源:

```css title="src/index.css"
.logo {
background-image: url('./assets/logo.png');
}
```

也支持使用**路径别名**来引用:

```css title="src/index.css"
.logo {
background-image: url('@/assets/logo.png');
}
```

在 [format](/config/lib/format) 为 `cjs` 或 `esm` 时,Rslib 会将产物视为需要被其他打包工具再次消费的中间产物,会通过设置 [output.assetPrefix](/config/rsbuild/output#outputassetprefix) 为 `"auto"` 使 CSS 产物中保留相对引用路径。

```css title="dist/index.css"
.logo {
background-image: url('./static/image/logo.png');
}
```

如果需要在 CSS 文件中引用绝对路径下的静态资源:

```css
@font-face {
font-family: DingTalk;
src: url('/image/font/foo.ttf');
}
```

默认情况下,Rslib 内置的 `css-loader` 会解析 `url()` 中的绝对路径并寻找指定的模块。如果你希望跳过绝对路径的解析,可以配置 [`tools.cssLoader`](/config/rsbuild/tools#toolscssloader) 来过滤指定的路径,被过滤的路径将被原样保留在代码中。

```ts
export default {
tools: {
cssLoader: {
url: {
filter: (url) => {
if (/\/image\/font/.test(url)) {
return false;
}
return true;
},
},
},
},
};
```

## 静态资源内联

在开发组件库场景,这种会被其他打包工具再次消费的中间产物时,一般不会内联静态资源,交给应用侧的构建工具处理和优化。

自动内联的体积阈值可以通过 [output.dataUriLimit](/config/rsbuild/output#outputdataurilimit) 配置项修改。在 [format](/config/lib/format) 为 `cjs` 或 `esm` 时,Rslib 默认会将 `output.dataUriLimit` 设置为 `0`,不内联任何静态资源。

## 构建产物目录

当静态资源被引用后,会自动被输出到构建产物的目录下,你可以:

- 通过 [output.filename](/config/rsbuild/output#outputfilename) 来修改产物的文件名。
- 通过 [output.distPath](/config/rsbuild/output#outputdistpath) 来修改产物的输出路径。

## 类型声明

当你在 TypeScript 代码中引用静态资源时,TypeScript 可能会提示该模块缺少类型定义:

```
TS2307: Cannot find module './logo.png' or its corresponding type declarations.
```

此时你需要为静态资源添加类型声明文件,请在项目中创建 `src/env.d.ts` 文件,并添加相应的类型声明。

- 方法一:如果项目里安装了 `@rslib/core` 包,你可以直接引用 `@rslib/core` 提供的**预设类型**:

```ts
/// <reference types="@rslib/core/types" />
```

- 方法二:手动添加需要的类型声明:

```ts title="src/env.d.ts"
// 以 png 图片为例
declare module '*.png' {
const url: string;
export default url;
}
```

添加类型声明后,如果依然存在上述错误提示,请尝试重启当前 IDE,或者调整 `env.d.ts` 所在的目录,使 TypeScript 能够正确识别类型定义。

## 扩展静态资源类型

如果 Rslib 内置的静态资源类型不能满足你的需求,可以通过以下方式扩展额外的静态资源类型。

### 使用 `source.assetsInclude`

通过 [source.assetsInclude](/config/rsbuild/source#sourceassetsinclude) 配置项,你可以指定需要被视为静态资源的额外文件类型。

```ts title="rslib.config.ts"
export default {
source: {
assetsInclude: /\.pdf$/,
},
};
```

添加以上配置后,你就可以在代码里引用 `*.pdf` 文件了,比如:

```js
import myFile from './static/myFile.pdf';

console.log(myFile); // "/static/assets/myFile.[hash].pdf"
```

### 使用 `tools.rspack`

可以通过 [tools.rspack](/config/rsbuild/tools#toolsrspack) 来修改内置的 Rspack 配置,并添加自定义的静态资源处理规则。

比如,把 `*.pdf` 文件当做静态资源输出到产物目录,可以添加以下配置:

```ts title="rslib.config.ts"
export default {
tools: {
rspack(config, { addRules }) {
addRules([
{
test: /\.pdf$/,
// 将资源转换为单独的文件,并且导出产物地址
type: 'asset/resource',
},
]);
},
},
};
```

关于 asset modules 的更多介绍,请参考 [Rspack - Asset modules](https://rspack.dev/guide/features/asset-module)。
Loading
Loading