Skip to content
Grok

Building for Production

ทำไมต้อง Build ก่อน Deploy?

เราใช้ Vite ในการ build โปรเจคเพื่อ:

  • เพิ่มประสิทธิภาพ: ทำให้แปรผลและโหลดเร็วขึ้น
  • ลดขนาดไฟล์: ด้วย minification, tree-shaking, และ code splitting
  • ปรับปรุงความปลอดภัย: ซ่อน source code และ implementation details
  • เพิ่มความเข้ากันได้: รองรับ browser เก่าๆ ด้วย polyfills
  • เพิ่มประสิทธิภาพ: ใช้ caching และ compression ที่เหมาะสม

ขั้นตอนการ Build พื้นฐาน

  1. กำหนด script build ใน package.json
json
{
	"scripts": {
		"build": "vite build",
		"preview": "vite preview"
	}
}
  1. กำหนดค่า build ใน vite.config.ts
ts
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    outDir: "dist",
    assetsDir: "assets",
    sourcemap: false, // เปิดเฉพาะตอน debug
    minify: "terser",
    terserOptions: {
      compress: {
        drop_console: true, // ลบ console.log ออก
      },
    },
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ["react", "react-dom"],
          utils: ["lodash", "date-fns"],
        },
      },
    },
  },
});
  1. รันคำสั่ง build
bash
npm run build
bash
pnpm run build
bash
yarn build
bash
bun run build
  1. ทดสอบ production build
bash
npm run preview

การปรับแต่งขั้นสูง

Code Splitting

ts
build: {
  rollupOptions: {
    output: {
      manualChunks: {
        react: ['react', 'react-dom'],
        vendor: ['lodash', 'axios'],
      },
    },
  },
}

กำหนด Browser Targets

ts
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    target: "es2015",
  },
});

กำหนด Public Path

ts
// สำหรับ deploy ย่อยใน subdirectory
base: '/my-app/',

build: {
  assetsDir: 'static',
}

กำหนด Environment Variables

สร้างไฟล์ .env.production:

txt
VITE_API_URL=https://api.example.com
VITE_APP_VERSION=$npm_package_version

การ Optimize รูปภาพ

ts
import { defineConfig } from "vite";
import { ViteImageOptimizer } from "vite-plugin-image-optimizer";

export default defineConfig({
  plugins: [
    ViteImageOptimizer({
      png: {
        quality: 80,
      },
      jpeg: {
        quality: 80,
      },
      jpg: {
        quality: 80,
      },
    }),
  ],
});

การ Deploy

Static Hosting

  1. Netlify

    • ติดตั้ง Netlify CLI: npm install -g netlify-cli
    • Deploy: netlify deploy --prod
  2. Vercel

    • ติดตั้ง Vercel CLI: npm i -g vercel
    • Deploy: vercel --prod

ใช้ Docker

สร้าง Dockerfile:

dockerfile
# Build stage
FROM node:18-alpine as build
WORK /app
COPY . .
RUN npm ci
RUN npm run build

# Production stage
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]