Skip to content

代碼語法

代碼是技術文檔中的重要元素。Markdown 提供了多種方式來顯示代碼,包括行內代碼和代碼塊。

行內代碼

基本語法

使用反引號 ` 包圍代碼:

markdown
這是一個 `行內代碼` 示例。
使用 `console.log()` 函數輸出信息。

渲染效果

這是一個 行內代碼 示例。 使用 console.log() 函數輸出信息。

包含反引號的代碼

當代碼本身包含反引號時,使用雙反引號:

markdown
``使用 `console.log()` 函數``

渲染效果

使用 `console.log()` 函數

多個反引號的處理

markdown
```包含多個反引號的代碼 `` ` ``` 在這裡```

渲染效果

包含多個反引號的代碼 `` ` 在這裡```

代碼塊

縮進代碼塊

使用 4 個空格或 1 個制表符縮進:

markdown
    function hello() {
        console.log("Hello, World!");
    }

渲染效果

function hello() {
    console.log("Hello, World!");
}

圍欄代碼塊

使用三個反引號 ``` 或波浪號 ~~~ 包圍代碼:

markdown
```
function hello() {
    console.log("Hello, World!");
}
```

渲染效果

function hello() {
    console.log("Hello, World!");
}

指定編程語言

在開頭的 ``` 後指定語言名稱以啟用語法高亮:

markdown
```javascript
function hello(name) {
    console.log(`Hello, ${name}!`);
}
```

渲染效果

javascript
function hello(name) {
    console.log(`Hello, ${name}!`);
}

常見編程語言示例

JavaScript

markdown
```javascript
// 異步函數示例
async function fetchData(url) {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error:', error);
    }
}
```

渲染效果

javascript
// 異步函數示例
async function fetchData(url) {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error:', error);
    }
}

Python

markdown
```python
# 類定義示例
class Calculator:
    def __init__(self):
        self.result = 0
    
    def add(self, x, y):
        return x + y
    
    def multiply(self, x, y):
        return x * y

# 使用示例
calc = Calculator()
print(calc.add(5, 3))
```

渲染效果

python
# 類定義示例
class Calculator:
    def __init__(self):
        self.result = 0
    
    def add(self, x, y):
        return x + y
    
    def multiply(self, x, y):
        return x * y

# 使用示例
calc = Calculator()
print(calc.add(5, 3))

HTML

markdown
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>示例頁面</title>
</head>
<body>
    <h1>歡迎使用 Markdown</h1>
    <p>這是一個示例段落。</p>
</body>
</html>
```

渲染效果

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>示例頁面</title>
</head>
<body>
    <h1>歡迎使用 Markdown</h1>
    <p>這是一個示例段落。</p>
</body>
</html>

CSS

markdown
```css
/* 響應式布局示例 */
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
}

@media (max-width: 768px) {
    .container {
        padding: 0 10px;
    }
}

.button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 4px;
    cursor: pointer;
}

.button:hover {
    background-color: #0056b3;
}
```

渲染效果

css
/* 響應式布局示例 */
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
}

@media (max-width: 768px) {
    .container {
        padding: 0 10px;
    }
}

.button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 4px;
    cursor: pointer;
}

.button:hover {
    background-color: #0056b3;
}

Bash/Shell

markdown
```bash
#!/bin/bash

# 腳本示例:批量處理文件
for file in *.txt; do
    if [ -f "$file" ]; then
        echo "Processing $file"
        cp "$file" "backup_$file"
    fi
done

# 函數定義
function check_dependencies() {
    command -v git >/dev/null 2>&1 || {
        echo "Git is required but not installed."
        exit 1
    }
}

check_dependencies
echo "All dependencies satisfied."
```

渲染效果

bash
#!/bin/bash

# 腳本示例:批量處理文件
for file in *.txt; do
    if [ -f "$file" ]; then
        echo "Processing $file"
        cp "$file" "backup_$file"
    fi
done

# 函數定義
function check_dependencies() {
    command -v git >/dev/null 2>&1 || {
        echo "Git is required but not installed."
        exit 1
    }
}

check_dependencies
echo "All dependencies satisfied."

JSON

markdown
```json
{
  "name": "markdown-tutorial",
  "version": "1.0.0",
  "description": "Markdown 中文教程",
  "main": "index.js",
  "scripts": {
    "dev": "vitepress dev docs",
    "build": "vitepress build docs",
    "preview": "vitepress preview docs"
  },
  "dependencies": {
    "vitepress": "^1.0.0"
  },
  "author": "Your Name",
  "license": "MIT"
}
```

渲染效果

json
{
  "name": "markdown-tutorial",
  "version": "1.0.0",
  "description": "Markdown 中文教程",
  "main": "index.js",
  "scripts": {
    "dev": "vitepress dev docs",
    "build": "vitepress build docs",
    "preview": "vitepress preview docs"
  },
  "dependencies": {
    "vitepress": "^1.0.0"
  },
  "author": "Your Name",
  "license": "MIT"
}

高級代碼塊功能

行號顯示

某些 Markdown 處理器支持顯示行號:

markdown
```javascript {1}
// 這是第一行
function example() {
    console.log("Hello");
}
```

行高亮

高亮特定行:

markdown
```javascript {2-3}
function example() {
    console.log("這行被高亮");  // 高亮
    return true;               // 高亮
}
```

文件名顯示

顯示代碼文件名:

markdown
```javascript title="app.js"
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello World!');
});
```

常見錯誤和解決方案

1. 反引號數量不匹配

markdown
❌ 錯誤:
```javascript
function hello() {
    console.log("Hello");
}
``  ← 反引號數量不匹配

✅ 正確:
```javascript
function hello() {
    console.log("Hello");
}
```

2. 縮進不一致

markdown
❌ 錯誤:縮進代碼塊
    第一行(4個空格)
  第二行(2個空格)  ← 縮進不一致

✅ 正確:縮進代碼塊
    第一行(4個空格)
    第二行(4個空格)

3. 語言名稱錯誤

markdown
❌ 錯誤:
```js  ← 應該是 javascript
function hello() {}
```

✅ 正確:
```javascript
function hello() {}
```

支持的語言列表

常見的語言標識符:

語言標識符示例
JavaScriptjavascript, jsfunction(){}
Pythonpython, pydef function():
Javajavapublic class{}
C++cpp, c++#include <iostream>
C#csharp, cspublic class{}
Gogofunc main(){}
Rustrust, rsfn main(){}
TypeScripttypescript, tsinterface{}
PHPphp<?php
Rubyruby, rbdef method
SQLsqlSELECT * FROM
HTMLhtml<div></div>
CSScss.class{}
XMLxml<root></root>
YAMLyaml, ymlkey: value
Markdownmarkdown, md# Title
Bashbash, sh#!/bin/bash
PowerShellpowershell, ps1Get-Process
DockerfiledockerfileFROM ubuntu

最佳實踐

1. 選擇合適的代碼格式

markdown
✅ 推薦:短代碼用行內格式
使用 `Array.map()` 方法處理數組。

✅ 推薦:長代碼用代碼塊
function processArray(arr) {
    return arr.map(item => item * 2);
}

2. 添加適當的注釋

markdown
✅ 推薦:包含解釋性注釋
```javascript
// 計算數組元素的平均值
function calculateAverage(numbers) {
    const sum = numbers.reduce((acc, num) => acc + num, 0);
    return sum / numbers.length;
}
```

3. 使用正確的語言標識符

markdown
✅ 推薦:明確的語言標識
```typescript
interface User {
    id: number;
    name: string;
}
```

❌ 不推薦:模糊的語言標識
```text
interface User {
    id: number;
    name: string;
}
```

4. 保持代碼簡潔

markdown
✅ 推薦:展示核心邏輯
```javascript
// 用戶認證
function authenticate(token) {
    return validateToken(token);
}
```

❌ 不推薦:包含過多細節
```javascript
// 這裡是很長的代碼,包含了很多不相關的細節...
```

HTML 輸出

Markdown 代碼轉換為 HTML:

markdown
`行內代碼`

轉換為:

html
<code>行內代碼</code>

代碼塊:

markdown
```javascript
function hello() {}
```

轉換為:

html
<pre><code class="language-javascript">
function hello() {}
</code></pre>

實用示例

API 文檔

markdown
## 用戶登錄

發送 POST 請求到 `/api/login`

```bash
curl -X POST https://api.example.com/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "password123"
  }'
```

響應示例:

```json
{
  "success": true,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": 1,
    "email": "user@example.com",
    "name": "張三"
  }
}
```

配置文件示例

markdown
## 項目配置

創建 `config.json` 文件:

```json
{
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp"
  },
  "server": {
    "port": 3000,
    "host": "0.0.0.0"
  }
}
```

更新 `package.json` 腳本:

```json
{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "jest"
  }
}
```

安裝指南

markdown
## 環境配置

1. 安裝 Node.js:

```bash
# macOS (使用 Homebrew)
brew install node

# Ubuntu/Debian
sudo apt update
sudo apt install nodejs npm

# Windows (使用 Chocolatey)
choco install nodejs
```

2. 驗證安裝:

```bash
node --version
npm --version
```

3. 初始化項目:

```bash
mkdir my-project
cd my-project
npm init -y
```

相關語法

練習

嘗試創建以下內容:

  1. 一個包含多種編程語言的代碼示例集合
  2. 一個 API 使用教程,包含請求和響應代碼
  3. 一個安裝指南,包含不同系統的命令行指令
  4. 一個配置文件模板,包含詳細的注釋說明

由 Markdownlang.com 整理創建