実用的な例
Text Diff ツールをさまざまなシナリオで使用する方法を示す実用的な例のコレクションです。
コード開発
JavaScript関数の更新
ファイルA(元のバージョン):
function calculateTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
return total;
}
ファイルB(改善版):
function calculateTotal(items) {
if (!items || items.length === 0) {
return 0;
}
return items.reduce((total, item) => {
return total + (item.price || 0);
}, 0);
}
Diff結果:
+ 2 2 | if (!items || items.length === 0) {
+ 3 3 | return 0;
+ 4 4 | }
+ 5 5 |
- 2 6 | let total = 0;
- 3 7 | for (let i = 0; i < items.length; i++) {
- 4 8 | total += items[i].price;
- 5 9 | }
- 6 10 | return total;
+ 6 7 | return items.reduce((total, item) => {
+ 7 8 | return total + (item.price || 0);
+ 8 9 | }, 0);
Reactコンポーネントのリファクタリング
ファイルA(クラスコンポーネント):
import React, { Component } from 'react';
class UserProfile extends Component {
constructor(props) {
super(props);
this.state = {
user: null,
loading: true,
};
}
componentDidMount() {
this.fetchUser();
}
fetchUser = async () => {
try {
const response = await fetch(`/api/users/${this.props.userId}`);
const user = await response.json();
this.setState({ user, loading: false });
} catch (error) {
console.error('Error fetching user:', error);
this.setState({ loading: false });
}
};
render() {
const { user, loading } = this.state;
if (loading) return <div>読み込み中...</div>;
if (!user) return <div>ユーザーが見つかりません</div>;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
}
ファイルB(フックを使用した関数コンポーネント):
import React, { useState, useEffect } from 'react';
const UserProfile = ({ userId }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchUser = async () => {
try {
const response = await fetch(`/api/users/${userId}`);
const userData = await response.json();
setUser(userData);
} catch (error) {
console.error('Error fetching user:', error);
} finally {
setLoading(false);
}
};
fetchUser();
}, [userId]);
if (loading) return <div>読み込み中...</div>;
if (!user) return <div>ユーザーが見つかりません</div>;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
};
設定管理
Docker Compose設定
ファイルA(開発環境):
version: '3.8'
services:
web:
build: .
ports:
- '3000:3000'
environment:
- NODE_ENV=development
- DATABASE_URL=postgresql://localhost:5432/myapp_dev
volumes:
- .:/app
- /app/node_modules
database:
image: postgres:13
environment:
- POSTGRES_DB=myapp_dev
- POSTGRES_USER=dev
- POSTGRES_PASSWORD=dev123
ports:
- '5432:5432'
ファイルB(本番環境):
version: '3.8'
services:
web:
build: .
ports:
- '80:3000'
environment:
- NODE_ENV=production
- DATABASE_URL=${DATABASE_URL}
restart: unless-stopped
depends_on:
- database
database:
image: postgres:13
environment:
- POSTGRES_DB=${POSTGRES_DB}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
volumes:
postgres_data:
Package.jsonの依存関係
ファイルA(更新前):
{
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"axios": "^0.21.1",
"lodash": "^4.17.20"
},
"devDependencies": {
"@types/react": "^17.0.0",
"typescript": "^4.2.3",
"webpack": "^5.24.0"
}
}
ファイルB(更新後):
{
"dependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
"axios": "^1.3.0",
"lodash": "^4.17.21"
},
"devDependencies": {
"@types/react": "^18.0.0",
"typescript": "^4.9.0",
"webpack": "^5.75.0",
"vite": "^4.0.0"
}
}
API開発
OpenAPI仕様
ファイルA(バージョン1.0):
openapi: 3.0.0
info:
title: User API
version: 1.0.0
description: ユーザー管理のためのAPI
paths:
/users:
get:
summary: すべてのユーザーを取得
responses:
'200':
description: ユーザーリスト
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
email:
type: string
ファイルB(バージョン2.0):
openapi: 3.0.0
info:
title: User API
version: 2.0.0
description: ユーザー管理のための改良されたAPI
paths:
/users:
get:
summary: すべてのユーザーを取得
parameters:
- name: limit
in: query
schema:
type: integer
default: 10
- name: offset
in: query
schema:
type: integer
default: 0
responses:
'200':
description: ページネーションされたユーザーリスト
content:
application/json:
schema:
$ref: '#/components/schemas/UserList'
'400':
description: 不正なリクエスト
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/users/{id}:
get:
summary: IDでユーザーを取得
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
'200':
description: ユーザーの詳細
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: ユーザーが見つかりません
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
email:
type: string
createdAt:
type: string
format: date-time
updatedAt:
type: string
format: date-time
UserList:
type: object
properties:
users:
type: array
items:
$ref: '#/components/schemas/User'
total:
type: integer
limit:
type: integer
offset:
type: integer
Error:
type: object
properties:
message:
type: string
code:
type: string
ドキュメント
README Markdown
ファイルA(基本バージョン):
# 私のプロジェクト
Reactで構築されたシンプルなWebアプリケーション。
## インストール
```bash
npm install
```
使用方法
npm start
機能
- ユーザー認証
- データ可視化
- レスポンシブデザイン
**ファイルB(拡張バージョン):**
```markdown
# 私のプロジェクト
リアルタイムデータ可視化と高度なユーザー管理機能を備えた、ReactとTypeScriptで構築されたモダンなWebアプリケーション。
## 目次
- [インストール](#インストール)
- [使用方法](#使用方法)
- [機能](#機能)
- [APIドキュメント](#apiドキュメント)
- [貢献](#貢献)
- [ライセンス](#ライセンス)
## インストール
### 前提条件
- Node.js 16.0以上
- npm 8.0以上
### セットアップ
```bash
# リポジトリをクローン
git clone https://github.com/user/my-project.git
cd my-project
# 依存関係をインストール
npm install
# 環境変数を設定
cp .env.example .env
使用方法
開発
npm run dev
本番
npm run build
npm start
機能
主要機能
- ユーザー認証: JWTトークンによる安全なログイン
- データ可視化: インタラクティブなグラフとテーブル
- レスポンシブデザイン: モバイルファーストアプローチ
- リアルタイム更新: WebSocket統合
- API統合: GraphQLサポート付きRESTful API
高度な機能
- ダークモード: ライトテーマとダークテーマの切り替え
- 国際化: 多言語サポート
- アクセシビリティ: WCAG 2.1 AA準拠
- パフォーマンス: 最適化されたバンドルサイズと読み込み時間
APIドキュメント
詳細なAPIドキュメントについてはAPI.mdを参照してください。
貢献
- リポジトリをフォーク
- 機能ブランチを作成
- 変更を加える
- テストを追加
- プルリクエストを送信
ライセンス
MITライセンス - 詳細はLICENSEを参照してください。
## データ分析
### **JSON設定**
**ファイルA(開発設定):**
```json
{
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp_dev",
"username": "dev_user",
"password": "dev_password"
},
"redis": {
"host": "localhost",
"port": 6379,
"password": null
},
"logging": {
"level": "debug",
"file": "logs/app.log"
},
"features": {
"enableAnalytics": false,
"enableDebugMode": true,
"enableExperimentalFeatures": true
}
}
ファイルB(本番設定):
{
"database": {
"host": "prod-db.example.com",
"port": 5432,
"name": "myapp_prod",
"username": "prod_user",
"password": "${DB_PASSWORD}",
"ssl": true,
"pool": {
"min": 5,
"max": 20
}
},
"redis": {
"host": "prod-redis.example.com",
"port": 6379,
"password": "${REDIS_PASSWORD}",
"cluster": {
"enabled": true,
"nodes": ["redis-1.example.com:6379", "redis-2.example.com:6379", "redis-3.example.com:6379"]
}
},
"logging": {
"level": "info",
"file": "/var/log/myapp/app.log",
"maxSize": "100MB",
"maxFiles": 5
},
"features": {
"enableAnalytics": true,
"enableDebugMode": false,
"enableExperimentalFeatures": false
},
"monitoring": {
"enabled": true,
"endpoint": "https://monitoring.example.com",
"apiKey": "${MONITORING_API_KEY}"
}
}
ベストプラクティス
効果的な使用
- 定期的な比較: 変更を追跡するためにファイルを定期的に比較
- 説明的な名前: ファイルに意味のある名前を使用
- 履歴の活用: 重要な比較を履歴に保存
- オプションの調整: 異なる比較オプションを試す
パフォーマンスのヒント
- ファイルサイズ: 最適なパフォーマンスのために10,000行未満のファイルを維持
- ブラウザキャッシュ: 問題がある場合はブラウザキャッシュをクリア
- モダンブラウザ: 最新のブラウザバージョンを使用
セキュリティの注意事項
- 機密データ: パスワードやAPIキーの比較を避ける
- ローカル処理: すべての処理がブラウザでローカルに実行
- 履歴のクリア: 履歴を定期的に削除
これらの例は、Text Diffツールの多様性とさまざまなアプリケーションシナリオでの威力を示しています。