코드 블록
문서 내에서 코드 블록을 사용하는 것은 매우 강력한 기능입니다 💪.
Code title
You can add a title to the code block by adding a title
key after the language (leave a space between them).
```jsx title="/src/components/HelloCodeTitle.js"
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
```
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
Syntax highlighting
코드 블록은 3개의 억음부호(`)로 감싼 텍스트 블록입니다. You may check out this reference for the specifications of MDX.
```js
console.log('Every repo must come with a mascot.');
```
Use the matching language meta string for your code block, and Docusaurus will pick up syntax highlighting automatically, powered by Prism React Renderer.
console.log('Every repo must come with a mascot.');
Theming
By default, the Prism syntax highlighting theme we use is Palenight. You can change this to another theme by passing theme
field in prism
as themeConfig
in your docusaurus.config.js.
For example, if you prefer to use the dracula
highlighting theme:
import {themes as prismThemes} from 'prism-react-renderer';
export default {
themeConfig: {
prism: {
theme: prismThemes.dracula,
},
},
};
Prism 테마는 JS 오브젝트일 뿐이므로 기본 설정이 맘에 들지 않는다면 자신만의 테마를 만들 수 있습니다. Docusaurus enhances the github
and vsDark
themes to provide richer highlight, and you can check our implementations for the light and dark code block themes.
Supported Languages
By default, Docusaurus comes with a subset of commonly used languages.
자바, C#, PHP 같은 일부 인기있는 언어도 기본적으로 활성화되지 않습니다.
To add syntax highlighting for any of the other Prism-supported languages, define it in an array of additional languages.
각 추가적인 언어는 유효한 Prism 컴포넌트 이름이어야 합니다. For example, Prism would map the language cs
to csharp
, but only prism-csharp.js
exists as a component, so you need to use additionalLanguages: ['csharp']
. You can look into node_modules/prismjs/components
to find all components (languages) available.
예를 들어 PowerShell 언어에 대한 구문 강조를 추가하려면 아래와 같이 설정합니다.
export default {
// ...
themeConfig: {
prism: {
additionalLanguages: ['powershell'],
},
// ...
},
};
After adding additionalLanguages
, restart Docusaurus.
If you want to add highlighting for languages not yet supported by Prism, you can swizzle prism-include-languages
:
- npm
- Yarn
- pnpm
npm run swizzle @docusaurus/theme-classic prism-include-languages
yarn swizzle @docusaurus/theme-classic prism-include-languages
pnpm run swizzle @docusaurus/theme-classic prism-include-languages
It will produce prism-include-languages.js
in your src/theme
folder. You can add highlighting support for custom languages by editing prism-include-languages.js
:
const prismIncludeLanguages = (Prism) => {
// ...
additionalLanguages.forEach((lang) => {
require(`prismjs/components/prism-${lang}`);
});
require('/path/to/your/prism-language-definition');
// ...
};
You can refer to Prism's official language definitions when you are writing your own language definitions.
When adding a custom language definition, you do not need to add the language to the additionalLanguages
config array, since Docusaurus only looks up the additionalLanguages
strings in languages that Prism provides. Adding the language import in prism-include-languages.js
is sufficient.
Line highlighting
Highlighting with comments
You can use comments with highlight-next-line
, highlight-start
, and highlight-end
to select which lines are highlighted.
```js
function HighlightSomeText(highlight) {
if (highlight) {
// highlight-next-line
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
function HighlightMoreText(highlight) {
// highlight-start
if (highlight) {
return 'This range is highlighted!';
}
// highlight-end
return 'Nothing highlighted';
}
```
function HighlightSomeText(highlight) {
if (highlight) {
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
function HighlightMoreText(highlight) {
if (highlight) {
return 'This range is highlighted!';
}
return 'Nothing highlighted';
}
지원하는 주석 구문은 아래와 같습니다.
스타일 | 구문 |
---|---|
C-style | /* ... */ and // ... |
JSX-style | {/* ... */} |
Bash-style | # ... |
HTML-style | <!-- ... --> |
We will do our best to infer which set of comment styles to use based on the language, and default to allowing all comment styles. 현재 지원되지 않는 주석 스타일은 추가할 수 있도록 열려있습니다! 풀 리퀘스트를 환영합니다. 다른 주석 스타일도 의미적인 차이는 없으며 내용만 다릅니다.
You can set your own background color for highlighted code line in your src/css/custom.css
which will better fit to your selected syntax highlighting theme. 아래 예제에서 사용한 색상은 기본 구문 강조 테마(Palenight)에 맞춘 색상입니다. 다른 테마를 사용한다면 적절한 색상으로 수정해주어야 합니다.
:root {
--docusaurus-highlighted-code-line-bg: rgb(72, 77, 91);
}
/* If you have a different syntax highlighting theme for dark mode. */
[data-theme='dark'] {
/* Color which works with dark mode syntax highlighting theme */
--docusaurus-highlighted-code-line-bg: rgb(100, 100, 100);
}
If you also need to style the highlighted code line in some other way, you can target on theme-code-block-highlighted-line
CSS class.
Highlighting with metadata string
언어 메타 문자열 내에서 강조 표시된 라인 범위를 지정할 수도 있습니다(언어 뒤에 공백을 둡니다). 여러 라인을 강조하고 싶다면 라인 번호를 콤마로 구분하거나 범위 구문을 사용해 설정합니다. This feature uses the parse-number-range
library and you can find more syntax on their project details.
```jsx {1,4-6,11}
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;
```
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;
가능한 경우 주석으로 하이라이트 처리하는 것을 선호합니다. 코드 내에서 하이라이트를 처리하면 코드 블록이 길어지더라도 라인수를 직접 체크할 필요가 없습니다. 라인을 추가/제거할 때도 라인 범위를 다시 조정하지 않아도 됩니다.
- ```jsx {3}
+ ```jsx {4}
function HighlightSomeText(highlight) {
if (highlight) {
+ console.log('Highlighted text found');
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
```
아래에서 매직 주석 시스템을 확장해 사용자 지정 지시문과 그 기능을 정의하는 방법을 소개합니다. 하이라이트 메타 문자열이 없는 경우에만 매직 주석이 구문 분석을 처리합니다.
Custom magic comments
// highlight-next-line
and // highlight-start
etc. are called "magic comments", because they will be parsed and removed, and their purposes are to add metadata to the next line, or the section that the pair of start- and end-comments enclose.
테마 설정을 통해 사용자 지정 매직 주석을 선언할 수 있습니다. For example, you can register another magic comment that adds a code-block-error-line
class name:
- docusaurus.config.js
- src/css/custom.css
- myDoc.md
export default {
themeConfig: {
prism: {
magicComments: [
// Remember to extend the default highlight class name as well!
{
className: 'theme-code-block-highlighted-line',
line: 'highlight-next-line',
block: {start: 'highlight-start', end: 'highlight-end'},
},
{
className: 'code-block-error-line',
line: 'This will error',
},
],
},
},
};
.code-block-error-line {
background-color: #ff000020;
display: block;
margin: 0 calc(-1 * var(--ifm-pre-padding));
padding: 0 var(--ifm-pre-padding);
border-left: 3px solid #ff000080;
}
In JavaScript, trying to access properties on `null` will error.
```js
const name = null;
// This will error
console.log(name.toUpperCase());
// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase')
```
자바스크립트에서 null
속성에 접근하려고 하면 오류가 발생합니다.
const name = null;
// 오류가 발생합니다.
console.log(name.toUpperCase());
// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase')
If you use number ranges in metastring (the {1,3-4}
syntax), Docusaurus will apply the first magicComments
entry's class name. This, by default, is theme-code-block-highlighted-line
, but if you change the magicComments
config and use a different entry as the first one, the meaning of the metastring range will change as well.
You can disable the default line highlighting comments with magicComments: []
. 매직 주석 구성은 없지만 도큐사우루스가 메타 문자열 범위를 포함하는 코드 블록을 발견하면 적용할 클래스 이름이 없기 때문에 오류가 발생합니다. 강조 표시되는 클래스 이름은 결국 매직 주석 항목일 뿐입니다.
Every magic comment entry will contain three keys: className
(required), line
, which applies to the directly next line, or block
(containing start
and end
), which applies to the entire block enclosed by the two comments.
Using CSS to target the class can already do a lot, but you can unlock the full potential of this feature through swizzling.
- npm
- Yarn
- pnpm
npm run swizzle @docusaurus/theme-classic CodeBlock/Line
yarn swizzle @docusaurus/theme-classic CodeBlock/Line
pnpm run swizzle @docusaurus/theme-classic CodeBlock/Line
The Line
component will receive the list of class names, based on which you can conditionally render different markup.
Line numbering
You can enable line numbering for your code block by using showLineNumbers
key within the language meta string (don't forget to add space directly before the key).
```jsx {1,4-6,11} showLineNumbers
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;
```
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;
Interactive code editor
(Powered by React Live)
You can create an interactive coding editor with the @docusaurus/theme-live-codeblock
plugin. 먼저 패키지에 플러그인을 추가해주세요.
- npm
- Yarn
- pnpm
npm install --save @docusaurus/theme-live-codeblock
yarn add @docusaurus/theme-live-codeblock
pnpm add @docusaurus/theme-live-codeblock
You will also need to add the plugin to your docusaurus.config.js
.
export default {
// ...
themes: ['@docusaurus/theme-live-codeblock'],
// ...
};
To use the plugin, create a code block with live
attached to the language meta string.
```jsx live
function Clock(props) {
const [date, setDate] = useState(new Date());
useEffect(() => {
const timerID = setInterval(() => tick(), 1000);
return function cleanup() {
clearInterval(timerID);
};
});
function tick() {
setDate(new Date());
}
return (
<div>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
```
코드 블록은 대화형 편집기로 변환됩니다. 코드를 변경하면 바로 결과창에 표시됩니다.
function Clock(props) { const [date, setDate] = useState(new Date()); useEffect(() => { const timerID = setInterval(() => tick(), 1000); return function cleanup() { clearInterval(timerID); }; }); function tick() { setDate(new Date()); } return ( <div> <h2>It is {date.toLocaleTimeString()}.</h2> </div> ); }
Imports
react-live 코드 편집기를 직접 가져올 수는 없습니다. 가져오기 할 항목을 미리 정의해야 합니다.
기본적으로 모든 리액트 가져오기를 지원합니다. 가져오기 기능을 사용하려면 react-live scope를 대체해주어야 합니다.
- npm
- Yarn
- pnpm
npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope -- --eject
yarn swizzle @docusaurus/theme-live-codeblock ReactLiveScope --eject
pnpm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope --eject
import React from 'react';
const ButtonExample = (props) => (
<button
{...props}
style={{
backgroundColor: 'white',
color: 'black',
border: 'solid red',
borderRadius: 20,
padding: 10,
cursor: 'pointer',
...props.style,
}}
/>
);
// Add react-live imports you need here
const ReactLiveScope = {
React,
...React,
ButtonExample,
};
export default ReactLiveScope;
The ButtonExample
component is now available to use:
function MyPlayground(props) { return ( <div> <ButtonExample onClick={() => alert('hey!')}>Click me</ButtonExample> </div> ); }
렌더링 명령(noInline)
The noInline
option should be used to avoid errors when your code spans multiple components or variables.
```jsx live noInline
const project = 'Docusaurus';
const Greeting = () => <p>Hello {project}!</p>;
render(<Greeting />);
```
Unlike an ordinary interactive code block, when using noInline
React Live won't wrap your code in an inline function to render it.
You will need to explicitly call render()
at the end of your code to display the output.
const project = "Docusaurus"; const Greeting = () => ( <p>Hello {project}!</p> ); render( <Greeting /> );
Using JSX markup in code blocks
마크다운 코드 블록은 항상 내용을 일반 텍스트로 유지하기 때문에 다음과 같은 작업은 할 수 없습니다.
type EditUrlFunction = (params: {
// This doesn't turn into a link (for good reason!)
version: <a href="/docs/versioning">Version</a>;
versionDocsDirPath: string;
docPath: string;
permalink: string;
locale: string;
}) => string | undefined;
If you want to embed HTML markup such as anchor links or bold type, you can use the <pre>
tag, <code>
tag, or <CodeBlock>
component.
<pre>
<b>Input: </b>1 2 3 4{'\n'}
<b>Output: </b>"366300745"{'\n'}
</pre>
Input: 1 2 3 4 Output: "366300745"
MDX is in line with JSX behavior: line break characters, even when inside <pre>
, are turned into spaces. 필요하다면 줄바꿈 문자를 명시적으로 작성해야 합니다.
구문 강조 표시는 일반 문자열에서만 작동합니다. 도큐사우루스는 JSX 자식을 포함하는 코드 블록 콘텐츠의 구문 분석은 하지 않습니다.
Multi-language support code blocks
MDX를 사용하면 문서 내에서 대화형 컴포넌트를 쉽게 만들 수 있습니다. 이를테면 여러 프로그래밍 언어의 코드를 보여주기 위해 탭 컴포넌트를 사용해서 사용자가 선택하게 할 수 있습니다.
Instead of implementing a dedicated component for multi-language support code blocks, we've implemented a general-purpose <Tabs>
component in the classic theme so that you can use it for other non-code scenarios as well.
아래 예제는 문서 내에서 여러 프로그래밍 언어를 지원하는 코드를 어떻게 처리할 수 있는지 보여줍니다. Note that the empty lines above and below each language block are intentional. This is a current limitation of MDX: you have to leave empty lines around Markdown syntax for the MDX parser to know that it's Markdown syntax and not JSX.
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs>
<TabItem value="js" label="JavaScript">
```js
function helloWorld() {
console.log('Hello, world!');
}
```
</TabItem>
<TabItem value="py" label="Python">
```py
def hello_world():
print("Hello, world!")
```
</TabItem>
<TabItem value="java" label="Java">
```java
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
```
</TabItem>
</Tabs>
화면에 보여지는 결과는 아래와 같습니다.
- JavaScript
- Python
- Java
function helloWorld() {
console.log('Hello, world!');
}
def hello_world():
print("Hello, world!")
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
If you have multiple of these multi-language code tabs, and you want to sync the selection across the tab instances, refer to the Syncing tab choices section.
Docusaurus npm2yarn remark plugin
npm과 Yarn 모두 CLI 명령을 표시하는 것은 매우 일반적인 요구 사항입니다. 예를 들면 다음과 같은 형식입니다.
- npm
- Yarn
- pnpm
npm install @docusaurus/remark-plugin-npm2yarn
yarn add @docusaurus/remark-plugin-npm2yarn
pnpm add @docusaurus/remark-plugin-npm2yarn
Docusaurus provides such a utility out of the box, freeing you from using the Tabs
component every time. To enable this feature, first install the @docusaurus/remark-plugin-npm2yarn
package as above, and then in docusaurus.config.js
, for the plugins where you need this feature (doc, blog, pages, etc.), register it in the remarkPlugins
option. (See Docs configuration for more details on configuration format)
export default {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
remarkPlugins: [
[require('@docusaurus/remark-plugin-npm2yarn'), {sync: true}],
],
},
pages: {
remarkPlugins: [require('@docusaurus/remark-plugin-npm2yarn')],
},
blog: {
remarkPlugins: [
[
require('@docusaurus/remark-plugin-npm2yarn'),
{converters: ['pnpm']},
],
],
// ...
},
},
],
],
};
And then use it by adding the npm2yarn
key to the code block:
```bash npm2yarn
npm install @docusaurus/remark-plugin-npm2yarn
```
Configuration
옵션 | 타입 | 기본값 | 설명 |
---|---|---|---|
sync | boolean | false | 선택한 컨버터를 모든 코드 블록에 동기화할지 여부를 설정합니다. |
converters | array | 'yarn' , 'pnpm' | 사용할 컨버터 목록입니다. 첫 번째 컨버터가 기본 선택으로 사용되므로 컨버터 목록의 순서가 중요합니다. |
Usage in JSX
Outside of Markdown, you can use the @theme/CodeBlock
component to get the same output.
import CodeBlock from '@theme/CodeBlock';
export default function MyReactPage() {
return (
<div>
<CodeBlock
language="jsx"
title="/src/components/HelloCodeTitle.js"
showLineNumbers>
{`function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}`}
</CodeBlock>
</div>
);
}
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
The props accepted are language
, title
and showLineNumbers
, in the same way as you write Markdown code blocks.
Although discouraged, you can also pass in a metastring
prop like metastring='{1-2} title="/src/components/HelloCodeTitle.js" showLineNumbers'
, which is how Markdown code blocks are handled under the hood. However, we recommend you use comments for highlighting lines.
As previously stated, syntax highlighting is only applied when the children is a simple string.