Code Hike 代码高亮示例

这篇文章展示了如何使用 Code Hike 进行代码高亮显示。

基础代码块

这是一个简单的 JavaScript 代码块:


_10
function greet(name) {
_10
console.log(`Hello, ${name}!`);
_10
return `Welcome, ${name}`;
_10
}
_10
_10
const message = greet("Code Hike");
_10
console.log(message);

TypeScript 示例

TypeScript 支持类型注解:


_32
interface User {
_32
id: number;
_32
name: string;
_32
email: string;
_32
isActive: boolean;
_32
}
_32
_32
class UserService {
_32
private users: User[] = [];
_32
_32
addUser(user: User): void {
_32
this.users.push(user);
_32
}
_32
_32
findUserById(id: number): User | undefined {
_32
return this.users.find(user => user.id === id);
_32
}
_32
_32
getAllActiveUsers(): User[] {
_32
return this.users.filter(user => user.isActive);
_32
}
_32
}
_32
_32
_32
_32
const userService = new UserService();
_32
userService.addUser({
_32
id: 1,
_32
name: "Alice",
_32
email: "alice@example.com",
_32
isActive: true
_32
});

one.py
two.py

_10
print("Hello, one!")

React 组件示例

使用 TypeScript 的 React 组件:


_62
import React, { useState, useEffect } from 'react';
_62
_62
interface TodoItem {
_62
id: number;
_62
text: string;
_62
completed: boolean;
_62
}
_62
_62
const TodoList: React.FC = () => {
_62
const [todos, setTodos] = useState<TodoItem[]>([]);
_62
const [inputValue, setInputValue] = useState('');
_62
_62
const addTodo = () => {
_62
if (inputValue.trim()) {
_62
const newTodo: TodoItem = {
_62
id: Date.now(),
_62
text: inputValue,
_62
completed: false
_62
};
_62
setTodos([...todos, newTodo]);
_62
setInputValue('');
_62
}
_62
};
_62
_62
const toggleTodo = (id: number) => {
_62
setTodos(todos.map(todo =>
_62
todo.id === id ? { ...todo, completed: !todo.completed } : todo
_62
));
_62
};
_62
_62
return (
_62
<div className="todo-container">
_62
<h1>我的待办事项</h1>
_62
<div className="input-group">
_62
<input
_62
type="text"
_62
value={inputValue}
_62
onChange={(e) => setInputValue(e.target.value)}
_62
onKeyPress={(e) => e.key === 'Enter' && addTodo()}
_62
placeholder="添加新任务..."
_62
/>
_62
<button onClick={addTodo}>添加</button>
_62
</div>
_62
<ul>
_62
{todos.map(todo => (
_62
<li
_62
key={todo.id}
_62
onClick={() => toggleTodo(todo.id)}
_62
style={{
_62
textDecoration: todo.completed ? 'line-through' : 'none',
_62
cursor: 'pointer'
_62
}}
_62
>
_62
{todo.text}
_62
</li>
_62
))}
_62
</ul>
_62
</div>
_62
);
_62
};
_62
_62
export default TodoList;

Python 示例

Python 数据处理示例:


_41
import pandas as pd
_41
import numpy as np
_41
from datetime import datetime
_41
_41
class DataProcessor:
_41
def __init__(self, data):
_41
self.data = pd.DataFrame(data)
_41
_41
def clean_data(self):
_41
"""清理数据:移除空值和重复项"""
_41
self.data = self.data.dropna()
_41
self.data = self.data.drop_duplicates()
_41
return self
_41
_41
def calculate_statistics(self):
_41
"""计算基本统计信息"""
_41
stats = {
_41
'mean': self.data.mean(),
_41
'median': self.data.median(),
_41
'std': self.data.std(),
_41
'min': self.data.min(),
_41
'max': self.data.max()
_41
}
_41
return stats
_41
_41
def filter_by_date(self, start_date, end_date):
_41
"""按日期范围筛选数据"""
_41
mask = (self.data['date'] >= start_date) & (self.data['date'] <= end_date)
_41
return self.data[mask]
_41
_41
# 使用示例
_41
data = {
_41
'date': pd.date_range('2024-01-01', periods=100),
_41
'value': np.random.randn(100),
_41
'category': np.random.choice(['A', 'B', 'C'], 100)
_41
}
_41
_41
processor = DataProcessor(data)
_41
processor.clean_data()
_41
stats = processor.calculate_statistics()
_41
print(stats)

CSS 样式示例

现代 CSS 特性:


_53
/* 变量定义 */
_53
:root {
_53
--primary-color: #3b82f6;
_53
--secondary-color: #8b5cf6;
_53
--text-color: #1f2937;
_53
--bg-color: #ffffff;
_53
--border-radius: 0.5rem;
_53
--spacing: 1rem;
_53
}
_53
_53
/* 渐变背景 */
_53
.hero-section {
_53
background: linear-gradient(
_53
135deg,
_53
var(--primary-color) 0%,
_53
var(--secondary-color) 100%
_53
);
_53
padding: calc(var(--spacing) * 4);
_53
border-radius: var(--border-radius);
_53
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
_53
}
_53
_53
/* Grid 布局 */
_53
.card-grid {
_53
display: grid;
_53
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
_53
gap: var(--spacing);
_53
padding: var(--spacing);
_53
}
_53
_53
/* 卡片样式 */
_53
.card {
_53
background: var(--bg-color);
_53
border-radius: var(--border-radius);
_53
padding: calc(var(--spacing) * 2);
_53
transition: transform 0.3s ease, box-shadow 0.3s ease;
_53
}
_53
_53
.card:hover {
_53
transform: translateY(-5px);
_53
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
_53
}
_53
_53
/* 响应式设计 */
_53
@media (max-width: 768px) {
_53
.card-grid {
_53
grid-template-columns: 1fr;
_53
}
_53
_53
.hero-section {
_53
padding: calc(var(--spacing) * 2);
_53
}
_53
}

SQL 查询示例

复杂的 SQL 查询:


_54
-- 创建用户表
_54
CREATE TABLE users (
_54
id SERIAL PRIMARY KEY,
_54
username VARCHAR(50) UNIQUE NOT NULL,
_54
email VARCHAR(100) UNIQUE NOT NULL,
_54
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
_54
is_active BOOLEAN DEFAULT true
_54
);
_54
_54
-- 创建文章表
_54
CREATE TABLE posts (
_54
id SERIAL PRIMARY KEY,
_54
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
_54
title VARCHAR(200) NOT NULL,
_54
content TEXT,
_54
views INTEGER DEFAULT 0,
_54
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
_54
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
_54
);
_54
_54
-- 复杂查询:获取活跃用户及其文章统计
_54
SELECT
_54
u.id,
_54
u.username,
_54
u.email,
_54
COUNT(p.id) as post_count,
_54
SUM(p.views) as total_views,
_54
AVG(p.views) as avg_views,
_54
MAX(p.created_at) as last_post_date
_54
FROM users u
_54
LEFT JOIN posts p ON u.id = p.user_id
_54
WHERE u.is_active = true
_54
GROUP BY u.id, u.username, u.email
_54
HAVING COUNT(p.id) > 0
_54
ORDER BY total_views DESC
_54
LIMIT 10;
_54
_54
-- 使用 CTE 的查询
_54
WITH monthly_stats AS (
_54
SELECT
_54
DATE_TRUNC('month', created_at) as month,
_54
COUNT(*) as post_count,
_54
SUM(views) as total_views
_54
FROM posts
_54
WHERE created_at >= NOW() - INTERVAL '1 year'
_54
GROUP BY DATE_TRUNC('month', created_at)
_54
)
_54
SELECT
_54
TO_CHAR(month, 'YYYY-MM') as month_name,
_54
post_count,
_54
total_views,
_54
ROUND(total_views::numeric / post_count, 2) as avg_views_per_post
_54
FROM monthly_stats
_54
ORDER BY month DESC;

Shell 脚本示例

自动化部署脚本:


_90
#!/bin/bash
_90
# 自动化部署脚本
_90
_90
# 颜色输出
_90
RED='\033[0;31m'
_90
GREEN='\033[0;32m'
_90
YELLOW='\033[1;33m'
_90
NC='\033[0m' # No Color
_90
_90
# 日志函数
_90
log_info() {
_90
echo -e "${GREEN}[INFO]${NC} $1"
_90
}
_90
_90
log_warn() {
_90
echo -e "${YELLOW}[WARN]${NC} $1"
_90
}
_90
_90
log_error() {
_90
echo -e "${RED}[ERROR]${NC} $1"
_90
}
_90
_90
# 检查依赖
_90
check_dependencies() {
_90
log_info "检查依赖..."
_90
_90
if ! command -v node &> /dev/null; then
_90
log_error "Node.js 未安装"
_90
exit 1
_90
fi
_90
_90
if ! command -v npm &> /dev/null; then
_90
log_error "npm 未安装"
_90
exit 1
_90
fi
_90
_90
log_info "依赖检查通过"
_90
}
_90
_90
# 构建项目
_90
build_project() {
_90
log_info "开始构建项目..."
_90
_90
npm install || {
_90
log_error "依赖安装失败"
_90
exit 1
_90
}
_90
_90
npm run build || {
_90
log_error "构建失败"
_90
exit 1
_90
}
_90
_90
log_info "项目构建成功"
_90
}
_90
_90
# 部署
_90
deploy() {
_90
log_info "开始部署..."
_90
_90
# 备份当前版本
_90
if [ -d "production" ]; then
_90
log_info "备份当前版本..."
_90
mv production "production.backup.$(date +%Y%m%d_%H%M%S)"
_90
fi
_90
_90
# 部署新版本
_90
mv build production
_90
_90
# 重启服务
_90
log_info "重启服务..."
_90
pm2 restart app || {
_90
log_error "服务重启失败"
_90
exit 1
_90
}
_90
_90
log_info "部署完成!"
_90
}
_90
_90
# 主流程
_90
main() {
_90
log_info "开始自动化部署流程..."
_90
check_dependencies
_90
build_project
_90
deploy
_90
log_info "所有步骤完成!"
_90
}
_90
_90
# 执行主流程
_90
main

JSON 配置示例


_31
{
_31
"name": "my-awesome-app",
_31
"version": "1.0.0",
_31
"description": "一个很棒的应用",
_31
"main": "index.js",
_31
"scripts": {
_31
"dev": "next dev",
_31
"build": "next build",
_31
"start": "next start",
_31
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
_31
"test": "jest --coverage"
_31
},
_31
"dependencies": {
_31
"next": "^14.0.0",
_31
"react": "^18.2.0",
_31
"react-dom": "^18.2.0"
_31
},
_31
"devDependencies": {
_31
"@types/node": "^20.0.0",
_31
"@types/react": "^18.2.0",
_31
"eslint": "^8.50.0",
_31
"typescript": "^5.2.0"
_31
},
_31
"keywords": [
_31
"nextjs",
_31
"react",
_31
"typescript"
_31
],
_31
"author": "Your Name",
_31
"license": "MIT"
_31
}

总结

Code Hike 提供了强大的代码高亮功能,支持:

  • ✅ 多种编程语言
  • ✅ 深色主题
  • ✅ 行号显示
  • ✅ 复制按钮
  • ✅ 语法高亮
  • ✅ 响应式设计

这使得技术文章的代码展示更加专业和易读!

Discussion4

Join the conversation

Sign in to share your thoughts and connect with others.

Sign In with GitHub
Michael Chang
Michael Chang·20h ago
The section on Context Windows vs RAG was really illuminating. I've been debating which approach to take for our internal knowledge base. Do you think the 1M+ context windows in newer models will eventually make RAG obsolete?
Sarah Chen
Sarah ChenAuthor·18h ago
Great question, Michael! I don't think RAG is going away anytime soon. Even with huge context windows, RAG offers better latency, cost-efficiency, and most importantly - the ability to cite sources explicitly.
Priya Patel
Priya Patel·Dec 22, 2025
I finally understand how Positional Encodings work! The visual analogy with the clock hands was brilliant. 👏
DevOps Ninja
DevOps Ninja·Dec 22, 2025
Any chance you could cover Quantization (GGUF/GPTQ) in a future post? trying to run these locally on my MacBook and it's a bit of a jungle out there.