前端工程化 · 69/90
1. Babel 的工作原理 2. body-parser 中间件的作用 3. Babel 转译原理 4. 浏览器和 Node 中的事件循环区别 5. 职责链模式 6. 链模式 7. 命令模式 8. 组件封装设计 9. 数据统计 10. dependencies 和 devDependencies 的区别 11. CommonJS 和 ES6 模块引入的区别 12. 设计模式分类 13. 前端开发中常用的设计模式 14. 设计模式应用场景 15. 设计原则 16. 开发环境搭建要点 17. Electron 理解 18. 前后端分离是什么 19. 工厂模式 20. 前端代码重构 21. 前端组件化 22. 前端工程师职业发展 23. 前端工程化方向 24. 前端工程化的理解 25. 前端工程价值体现 26. 前端工程化 27. Git 常用命令与工作流 28. Gulp 任务自动化工具 29. 图片导出 30. 前端模块化规范 31. 迭代器模式 32. JavaScript 编码规范 33. 前端 CI/CD 流程 34. jQuery 生态对比 35. jQuery 实现原理 36. jQuery 与 Sizzle 选择器集成 37. Koa 中间件异常处理 38. jQuery 源码优秀实践 39. jQuery 与 Zepto 对比 40. jQuery UI 自定义组件 41. Koa 中间件不调用 await next() 的影响 42. Koa 在没有 async/await 时如何实现洋葱模型 43. Koa 和 Express 的区别 44. Koa 洋葱模型 45. 登录实现 46. 中介者模式 47. 模块模式 48. 小程序架构 49. 小程序常见问题 50. Monorepo 概念与工具 51. mpvue 框架 52. MVC vs MVP vs MVVM 53. Node.js ES Module 为什么必须加文件扩展名 54. MVC、MVP 和 MVVM 架构模式 55. Node.js 全局对象 56. Node.js 性能监控与优化 57. Node.js 多进程与进程通讯 58. Node.js 调试方法 59. Node.js 中的 process 对象 60. Node.js 的理解与应用场景 61. npm 是什么? 62. 观察者模式和发布订阅模式的区别 63. 页面重构方法 64. PM2 守护进程原理 65. 分页功能的前后端设计 66. PostCSS 作用 67. 项目管理方法 68. Rollup 打包工具 69. 高质量前端代码 70. JavaScript 单例模式实现 71. SSG 静态网站生成 72. 模板方法模式 73. 设计模式的六大原则 74. Tree Shaking 原理 75. 用户授权信息获取流程 76. Vite 原理与性能优势 77. Web App vs Hybrid App vs Native App 78. Web 前端开发注意事项 79. Web APP 设计原则 80. Webpack 构建流程 81. Hash vs ChunkHash vs ContentHash 82. Webpack 热更新原理 83. Webpack Loader 与 Plugin 区别 84. webpack 的 module、bundle、chunk 是什么 85. Webpack Proxy 工作原理与跨域解决 86. webpack、rollup、parcel 的选择 87. WePy 与 mpvue 对比 88. WXML 和 WXSS 89. Webpack Scope Hoisting 90. Zepto 实现原理

高质量前端代码

好的前端代码应该具备哪些特征

问题

什么样的前端代码是好的?如何评判代码质量?

解答

好的前端代码具备以下特征:可读、可维护、可测试、高性能、健壮。

1. 可读性

差的代码:

// 命名模糊,逻辑混乱
function fn(a, b, c) {
  return a.filter(x => x.d > b && x.e < c).map(x => ({ ...x, f: x.d * 0.8 }))
}

好的代码:

// 命名清晰,意图明确
function filterProductsByPriceRange(products, minPrice, maxPrice) {
  const isInPriceRange = (product) => 
    product.price >= minPrice && product.price <= maxPrice

  const applyDiscount = (product) => ({
    ...product,
    discountedPrice: product.price * 0.8
  })

  return products
    .filter(isInPriceRange)
    .map(applyDiscount)
}

2. 可维护性

差的代码:

// 高耦合,难以修改
class UserPage {
  async loadData() {
    const res = await fetch('/api/user')
    const user = await res.json()
    document.getElementById('name').innerText = user.name
    document.getElementById('avatar').src = user.avatar
    localStorage.setItem('user', JSON.stringify(user))
  }
}

好的代码:

// 职责分离,低耦合
// api.js - 数据获取
export const fetchUser = () => fetch('/api/user').then(res => res.json())

// storage.js - 存储逻辑
export const saveUser = (user) => localStorage.setItem('user', JSON.stringify(user))

// UserPage.js - 页面逻辑
class UserPage {
  constructor(api, storage, renderer) {
    this.api = api
    this.storage = storage
    this.renderer = renderer
  }

  async loadData() {
    const user = await this.api.fetchUser()
    this.storage.saveUser(user)
    this.renderer.render(user)
  }
}

3. 可测试性

差的代码:

// 依赖全局状态,无法单元测试
function calculateTotal() {
  const items = window.cartItems
  const discount = window.userDiscount
  return items.reduce((sum, item) => sum + item.price, 0) * discount
}

好的代码:

// 纯函数,易于测试
function calculateTotal(items, discount = 1) {
  if (!Array.isArray(items)) return 0
  
  const subtotal = items.reduce((sum, item) => sum + (item.price || 0), 0)
  return subtotal * discount
}

// 测试用例
console.assert(calculateTotal([{ price: 100 }, { price: 200 }], 0.9) === 270)
console.assert(calculateTotal([], 1) === 0)
console.assert(calculateTotal(null) === 0)

4. 性能

差的代码:

// 每次渲染都创建新函数和新对象
function ProductList({ products }) {
  return (
    <ul>
      {products.map(p => (
        <li 
          key={p.id} 
          style={{ color: 'blue' }}
          onClick={() => console.log(p.id)}
        >
          {p.name}
        </li>
      ))}
    </ul>
  )
}

好的代码:

// 缓存函数和样式
const itemStyle = { color: 'blue' }

function ProductItem({ product, onClick }) {
  return (
    <li style={itemStyle} onClick={onClick}>
      {product.name}
    </li>
  )
}

function ProductList({ products }) {
  const handleClick = useCallback((id) => {
    console.log(id)
  }, [])

  return (
    <ul>
      {products.map(p => (
        <ProductItem 
          key={p.id} 
          product={p} 
          onClick={() => handleClick(p.id)}
        />
      ))}
    </ul>
  )
}

5. 健壮性

差的代码:

// 没有错误处理
async function getUserName(userId) {
  const res = await fetch(`/api/users/${userId}`)
  const data = await res.json()
  return data.profile.name
}

好的代码:

// 完善的错误处理
async function getUserName(userId) {
  if (!userId) {
    throw new Error('userId is required')
  }

  try {
    const res = await fetch(`/api/users/${userId}`)
    
    if (!res.ok) {
      throw new Error(`HTTP error: ${res.status}`)
    }
    
    const data = await res.json()
    return data?.profile?.name ?? 'Unknown'
    
  } catch (error) {
    console.error('Failed to fetch user:', error)
    throw error
  }
}

关键点

  • 命名清晰:变量、函数名能准确表达意图,不用缩写和单字母
  • 职责单一:每个函数/模块只做一件事,便于复用和修改
  • 纯函数优先:减少副作用,输入输出可预测,方便测试
  • 防御性编程:处理边界情况、空值、异常,代码不会意外崩溃
  • 适度抽象:不过早优化,不过度设计,在可读性和复用性间平衡