静态资源
静态资源是会被直接复制到构建输出的非代码文件。 它们包括图像、样式表、图标、字体等。
By default, you are suggested to put these assets in the static
folder. Every file you put into that directory will be copied into the root of the generated build
folder with the directory hierarchy preserved. 举个例子, if you add a file named sun.jpg
to the static folder, it will be copied to build/sun.jpg
.
这意味着:
- for site
baseUrl: '/'
, the image/static/img/docusaurus.png
will be served at/img/docusaurus.png
. - for site
baseUrl: '/subpath/'
, the image/static/img/docusaurus.png
will be served at/subpath/img/docusaurus.png
.
You can customize the static directory sources in docusaurus.config.js
. For example, we can add public
as another possible path:
export default {
title: 'My site',
staticDirectories: ['public', 'static'],
// ...
};
Now, all files in public
as well as static
will be copied to the build output.
Referencing your static asset
In JSX
In JSX, you can reference assets from the static
folder in your code using absolute URLs, 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
.
You can import()
or require()
the static asset (recommended), or use the useBaseUrl
utility function: both prepend the baseUrl
to paths for you.
示例:
import DocusaurusImageUrl from '@site/static/img/docusaurus.png';
<img src={DocusaurusImageUrl} />;
<img src={require('@site/static/img/docusaurus.png').default} />
import useBaseUrl from '@docusaurus/useBaseUrl';
<img src={useBaseUrl('/img/docusaurus.png')} />;
你也可以导入 SVG 文件:它会被自动转换为 React 组件。
import DocusaurusLogoWithKeytar from '@site/static/img/docusaurus_keytar.svg';
<DocusaurusLogoWithKeytar title="Docusaurus Logo" className="logo" />;