跳转至主内容
Version: 2.0.0-beta.10 🚧

静态资源

每个网站都需要静态资源:图像、样式表、图标等等。 By default, you are suggested to put these assets in the static folder.

放入此文件夹中的每个文件将自动复制进生成的 build 文件夹的根目录,同时保留其目录结构。 举个例子, 若您向 static 文件夹添加了 sun.jpg 文件,则其将会被复制到 build/sun.jpg 下。

这意味着:

  • 若设置 baseUrl: '/',则图像 /static/img/docusaurus.png 将位于 /img/docusaurus.png 处;
  • 若设置 baseUrl: '/子目录/',则图像 /static/img/docusaurus.png 将位于 /子目录/img/docusaurus.png 处。

You can customize the static directory sources in docusaurus.config.js. For example, we can add public as another possible path:

docusaurus.config.js
module.exports = {
title: 'My site',
staticDirectories: ['public', 'static'],
// ...
};

Now, all files in public as well as static will be copied to the build output.

引用您的静态资源

In JSX, you can reference assets from the static folder in your code using absolute paths, but this is not ideal because changing the site baseUrl will break those links. For the image <img src="/img/docusaurus.png" /> served at https://example.com/test, the browser will try to resolve it from the URL root, i.e. as https://example.com/img/docusaurus.png, which will fail because it's actually served at https://example.com/test/img/docusaurus.png.

我们推荐您 import / require() 静态资源,或使用 useBaseUrl 工具函数:两者都能为您在网址前加上 baseUrl

信息

In Markdown, things are different: you can stick to use absolute paths because Docusaurus actually handles them as require calls instead of URLs when parsing the Markdown. See Markdown static assets.

Examples

MyComponent.js
import DocusaurusImageUrl from '@site/static/img/docusaurus.png';

<img src={DocusaurusImageUrl} />;
MyComponent.js
<img src={require('@site/static/img/docusaurus.png').default} />
MyComponent.js
import useBaseUrl from '@docusaurus/useBaseUrl';

<img src={useBaseUrl('/img/docusaurus.png')} />;

您也可以导入 SVG 文件,其将被自动转换至 React 组件。

MyComponent.js
import DocusaurusLogoWithKeytar from '@site/static/img/docusaurus_keytar.svg';

<DocusaurusLogoWithKeytar title="Docusaurus Logo" className="logo" />;

提醒

有几点需要留意:

  • 默认情况下,static 内的文件都不会被后处理、散列或精简;
  • 使用硬编码的绝对路径引用的缺失文件无法在编译时被检测到,这会导致 404 错误;
  • 默认情况下,GitHub Pages 通过 Jekyll 运行已发布的文件。 由于 Jekyll 忽略任意以 _ 开头的文件,所以若您使用 GitHub Pages,我们推荐您在 static 文件夹中新建 .nojekyll 文件来禁用 Jekyll。