# Build Static Guide - Samatortrack Frontend

## Overview
Panduan lengkap untuk build static aplikasi Vue.js/Quasar frontend menjadi file HTML, CSS, JS yang dapat di-deploy ke web server.

## Prerequisites
- Node.js dan npm sudah terinstall
- Dependencies sudah terinstall (`npm install`)
- Environment variables sudah dikonfigurasi

## Build Commands

### 1. Development Build
```bash
cd frontend
npm run dev
# Menjalankan development server di http://localhost:5173
```

### 2. Production Build
```bash
cd frontend
npm run build
# Membuat static files di folder 'dist'
```

### 3. Preview Production Build
```bash
cd frontend
npm run preview
# Preview hasil build di http://localhost:4173
```

## Environment Configuration

### 1. Development Environment
**File**: `frontend/.env.development`
```env
VITE_API_BASE_URL=http://localhost:8000
VITE_APP_ENV=development
VITE_APP_NAME=Samatortrack Dev
VITE_DEBUG=true
```

### 2. Production Environment
**File**: `frontend/.env.production`
```env
VITE_API_BASE_URL=https://api.samatortrack.id
VITE_APP_ENV=production
VITE_APP_NAME=Samatortrack
VITE_DEBUG=false
```

## Build Process Step by Step

### Step 1: Prepare Environment
```bash
# 1. Masuk ke folder frontend
cd frontend

# 2. Install dependencies (jika belum)
npm install

# 3. Verify environment files
ls -la .env*
```

### Step 2: Build for Production
```bash
# Build dengan production environment
npm run build

# Output akan muncul di folder 'dist'
```

### Step 3: Verify Build Output
```bash
# Check build output
ls -la dist/

# Expected files:
# - index.html (main HTML file)
# - assets/ (CSS, JS, images)
# - favicon.ico
# - images/ (static assets)
```

## Build Output Structure
```
frontend/dist/
├── index.html              # Main HTML file
├── favicon.ico             # Favicon
├── images/                 # Static images
│   ├── samator-background.jpg
│   └── samatortrack-logo.png
└── assets/                 # Compiled assets
    ├── index-[hash].js     # Main JavaScript bundle
    ├── index-[hash].css    # Main CSS bundle
    └── vendor-[hash].js    # Vendor libraries
```

## Deployment Options

### Option 1: Deploy ke Web Server (Apache/Nginx)
```bash
# 1. Build aplikasi
npm run build

# 2. Copy semua file dari 'dist' ke web server
cp -r dist/* /var/www/html/

# 3. Configure web server untuk SPA routing
```

### Option 2: Deploy ke PHP Server (Hybrid)
```bash
# 1. Build aplikasi
npm run build

# 2. Copy ke public folder PHP project
cp -r dist/* ../public/

# 3. Update public/index.php untuk handle SPA routing
```

### Option 3: Deploy ke CDN/Static Hosting
```bash
# 1. Build aplikasi
npm run build

# 2. Upload folder 'dist' ke:
# - Netlify
# - Vercel
# - GitHub Pages
# - AWS S3 + CloudFront
```

## Web Server Configuration

### Apache (.htaccess)
**File**: `dist/.htaccess`
```apache
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

# Enable compression
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/xml
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

# Cache static assets
<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresByType text/css "access plus 1 year"
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/jpg "access plus 1 year"
  ExpiresByType image/jpeg "access plus 1 year"
</IfModule>
```

### Nginx Configuration
```nginx
server {
    listen 80;
    server_name your-domain.com;
    root /var/www/html;
    index index.html;

    # Handle SPA routing
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Cache static assets
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Gzip compression
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
```

## PHP Integration (Hybrid Deployment)

### Update public/index.php
```php
<?php
// Existing PHP backend code...

// Handle SPA routing - serve index.html for non-API routes
$requestUri = $_SERVER['REQUEST_URI'];
$scriptName = $_SERVER['SCRIPT_NAME'];
$pathInfo = parse_url($requestUri, PHP_URL_PATH);

// Check if it's an API request
if (strpos($pathInfo, '/api/') === 0 || 
    strpos($pathInfo, '/crud/') === 0 || 
    strpos($pathInfo, '/auth/') === 0) {
    // Handle API requests
    // ... existing API routing code
} else {
    // Check if file exists (for static assets)
    $filePath = __DIR__ . $pathInfo;
    if (file_exists($filePath) && is_file($filePath)) {
        // Serve static file
        $mimeType = mime_content_type($filePath);
        header('Content-Type: ' . $mimeType);
        readfile($filePath);
        exit;
    } else {
        // Serve SPA index.html for all other routes
        header('Content-Type: text/html');
        readfile(__DIR__ . '/index.html');
        exit;
    }
}
?>
```

## Build Optimization

### 1. Vite Configuration Enhancement
**File**: `frontend/vite.config.js`
```javascript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { quasar, transformAssetUrls } from '@quasar/vite-plugin'
import { fileURLToPath, URL } from 'node:url'

export default defineConfig({
  plugins: [
    vue({
      template: { transformAssetUrls }
    }),
    quasar({
      // sassVariables: 'src/quasar-variables.sass'
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  build: {
    // Output directory
    outDir: 'dist',
    
    // Generate sourcemaps for debugging
    sourcemap: false,
    
    // Minify output
    minify: 'terser',
    
    // Chunk size warning limit
    chunkSizeWarningLimit: 1000,
    
    // Rollup options
    rollupOptions: {
      output: {
        // Manual chunks for better caching
        manualChunks: {
          vendor: ['vue', 'vue-router', 'quasar'],
          utils: ['axios']
        }
      }
    }
  }
})
```

### 2. Package.json Scripts Enhancement
```json
{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "build:analyze": "vite build --mode analyze",
    "preview": "vite preview",
    "clean": "rm -rf dist",
    "build:clean": "npm run clean && npm run build"
  }
}
```

## Testing Build

### 1. Local Testing
```bash
# Build aplikasi
npm run build

# Test dengan preview server
npm run preview

# Buka http://localhost:4173
# Test semua fitur aplikasi
```

### 2. Production Testing
```bash
# Deploy ke staging server
# Test dengan production API
# Verify semua environment variables
# Test performance dan loading speed
```

## Performance Optimization

### 1. Code Splitting
- Automatic code splitting by Vite
- Manual chunks untuk vendor libraries
- Lazy loading untuk routes

### 2. Asset Optimization
- Image compression
- CSS minification
- JavaScript minification
- Gzip compression

### 3. Caching Strategy
- Static assets: 1 year cache
- HTML: No cache (untuk updates)
- API responses: Appropriate cache headers

## Troubleshooting

### Common Issues

#### 1. Blank Page After Build
```bash
# Check console for errors
# Verify API base URL in production
# Check routing configuration
```

#### 2. Assets Not Loading
```bash
# Verify base path in vite.config.js
# Check web server configuration
# Verify file permissions
```

#### 3. API Calls Failing
```bash
# Check CORS configuration
# Verify production API URL
# Check network requests in DevTools
```

## Build Commands Summary

```bash
# Development
npm run dev                 # Start dev server

# Production Build
npm run build              # Build for production
npm run preview            # Preview production build

# Maintenance
npm run clean              # Clean dist folder
npm run build:clean        # Clean and build
```

## Deployment Checklist

- [ ] Environment variables configured
- [ ] API endpoints accessible
- [ ] Build completed successfully
- [ ] Static files copied to server
- [ ] Web server configured for SPA
- [ ] HTTPS configured (if needed)
- [ ] Performance tested
- [ ] All features working
- [ ] Error handling tested

## Author
**Rodhi** - Full Stack Developer

## Date
January 20, 2026

## Status
✅ **READY** - Build static guide lengkap dan siap untuk deployment