There are plenty of articles online about how frontend routing works, but most lack real-world experience. Drawing on actual projects, this article explores best practices.
Quick Start
Here is a concrete example:
javascript
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-gap: 1.5rem;
}
.grid__item {
display: flex;
flex-direction: column;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
transition: transform 0.2s, box-shadow 0.2s;
}
.grid__item:hover {
transform: translateY(-4px);
box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}
After rolling this pattern out across the team, the results were positive and maintenance cost dropped noticeably.
Advanced Usage
We can implement it in the following way:
javascript
:root {
--primary: #3498db;
--bg: #fff;
--text: #333;
}
[data-theme='dark'] {
--primary: #5dade2;
--bg: #1a1a2e;
--text: #eee;
}
body {
background: var(--bg);
color: var(--text);
transition: background 0.3s, color 0.3s;
}
Pay attention to the performance details in the code above and avoid unnecessary computation.
Business Scenarios
Refer to the code below for the concrete implementation:
javascript
const express = require('express')
const app = express()
// 中间件
app.use(express.json())
function errorHandler(err, req, res, next) {
console.error(err.stack)
res.status(500).json({
error: process.env.NODE_ENV === 'production'
? '服务器错误' : err.message
})
}
app.get('/api/users', async (req, res, next) => {
try {
const users = await User.find()
res.json(users)
} catch (err) {
next(err)
}
})
app.use(errorHandler)
This solution has been validated in production and runs stably.
Pitfall Avoidance Guide
Let's start with the basic usage:
javascript
const http = require('http')
const cluster = require('cluster')
const os = require('os')
if (cluster.isMaster) {
const numWorkers = os.cpus().length
console.log(`主进程 ${process.pid},启动 ${numWorkers} 个 worker`)
for (let i = 0; i < numWorkers; i++) {
cluster.fork()
}
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} 退出,重启中`)
cluster.fork()
})
} else {
http.createServer((req, res) => {
res.end(`Worker ${process.pid}`)
}).listen(3000)
}
This approach is clean and clear, and works well for most scenarios.
Summary
- Consistent team conventions matter more than chasing a perfect implementation
- Keep learning and summarizing to stay technically sharp
- When you hit a problem, read the source code and the official docs
