Skip to content
⚠️ This article was written in 2022. Some content may be outdated.

VitePress でドキュメントサイトを構築する

关于VitePress 文档站搭建实践,很多开发者只停留在 API 调用层面。本文试图从生产环境的角度,讨论实际中会遇到的问题和解决方案。

基本原理

まず基本的な実装方法から見てみましょう:

javascript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig({
  plugins: [vue()],
  resolve: { alias: { '@': resolve(__dirname, 'src') } },
  server: {
    port: 3000,
    proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true } }
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['vue', 'vue-router', 'pinia'],
          utils: ['lodash-es', 'dayjs']
        }
      }
    }
  }
})

このコードは基本的な使用方法を示しています。実際のプロジェクトでは、エラー処理とエッジケースも考慮する必要があります。

高度な機能

この基盤の上で、さらに最適化できます:

javascript
import { reactive, toRefs, computed } from 'vue'

function useCounter(initial = 0) {
  const state = reactive({ count: initial, history: [initial] })
  const doubled = computed(() => state.count * 2)

  function increment() {
    state.count++
    state.history.push(state.count)
  }

  return { ...toRefs(state), doubled, increment }
}

このパターンは大規模プロジェクトで非常に実用的で、メンテナンスコストを大幅に削減できます。

プロジェクト実践

実際のプロジェクトでの使い方はより複雑になります:

javascript
import { ref, computed, watch, onMounted } from 'vue'

export default {
  setup() {
    const count = ref(0)
    const doubled = computed(() => count.value * 2)

    watch(count, (newVal, oldVal) => {
      console.log(`count: ${oldVal} -> ${newVal}`)
    })

    onMounted(() => { console.log('组件已挂载') })

    return { count, doubled }
  }
}

このアプローチにより、コードのテスト可能性とスケーラビリティの両方が向上します。

ベストプラクティス

以下は完全な例です:

javascript
module.exports = {
  entry: './src/index.js',
  output: { path: __dirname + '/dist', filename: '[name].[contenthash:8].js' },
  module: {
    rules: [
      { test: /\.jsx?$/, exclude: /node_modules/, use: 'babel-loader' },
      { test: /\.css$/, use: ['style-loader', 'css-loader', 'postcss-loader'] }
    ]
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors' }
      }
    }
  }
}

境界条件の処理に注意してください。これは本番環境において非常に重要です。

まとめ

  • 新技術のために新技術を採用しないでください
  • コード例は参考のみであり、ビジネスシナリオに応じて調整が必要です
  • VitePress 文档站搭建实践は銀の弾丸ではなく、プロジェクトの規模と技術スタックに応じて選択する必要があります

MIT Licensed