Advanced Usage
Advanced CLI workflows and complex project setups
Advanced Usage
Learn advanced FoundryKit CLI workflows for complex project setups and custom configurations.
Custom Templates
Creating Custom Component Templates
Create custom templates for component generation.
# Create template directory
mkdir -p templates/components
# Create component template
cat > templates/components/component.tsx << 'EOF'
import React from 'react'
import { cn } from '@/lib/utils'
interface {{name}}Props {
className?: string
children?: React.ReactNode
}
export function {{name}}({ className, children, ...props }: {{name}}Props) {
return (
<div className={cn('{{name}}-component', className)} {...props}>
{children}
</div>
)
}
EOF
Template Configuration
Configure the CLI to use your custom templates.
// foundrykit.config.js
module.exports = {
components: {
templates: {
component: './templates/components/component.tsx',
test: './templates/components/component.test.tsx',
story: './templates/components/component.stories.tsx',
index: './templates/components/index.ts'
}
}
}
Template Variables
Use template variables in your custom templates.
// templates/components/component.tsx
import React from 'react'
import { cn } from '@/lib/utils'
interface {{name}}Props {
className?: string
children?: React.ReactNode
variant?: '{{variants}}'
size?: '{{sizes}}'
}
export function {{name}}({
className,
children,
variant = 'default',
size = 'md',
...props
}: {{name}}Props) {
return (
<div
className={cn(
'{{name}}-component',
`{{name}}-${variant}`,
`{{name}}-${size}`,
className
)}
{...props}
>
{children}
</div>
)
}
Custom Scripts
Creating Custom CLI Scripts
Extend the CLI with custom scripts.
// scripts/custom-script.js
#!/usr/bin/env node
const { program } = require('commander')
const fs = require('fs')
const path = require('path')
program
.command('generate-api')
.description('Generate API client from OpenAPI spec')
.option('-s, --spec <path>', 'OpenAPI spec file path')
.option('-o, --output <path>', 'Output directory')
.action((options) => {
// Custom API generation logic
console.log('Generating API client...')
// Implementation here
})
program.parse()
Registering Custom Scripts
Register your custom scripts with the CLI.
// foundrykit.config.js
module.exports = {
scripts: {
'generate-api': './scripts/custom-script.js generate-api',
'setup-db': './scripts/setup-database.js',
'deploy-staging': './scripts/deploy.js staging'
}
}
Monorepo Configuration
Multi-Package Setup
Configure the CLI for monorepo projects.
// foundrykit.config.js
module.exports = {
monorepo: {
enabled: true,
packages: [
'packages/components',
'packages/hooks',
'packages/utils',
'apps/web',
'apps/docs'
],
workspace: {
npm: true,
yarn: true,
pnpm: true
}
},
// Package-specific configurations
packages: {
'packages/components': {
build: {
outDir: 'dist',
entry: 'src/index.ts'
}
},
'apps/web': {
dev: {
port: 3000
},
build: {
outDir: 'dist'
}
}
}
}
Cross-Package Commands
Run commands across multiple packages.
# Build all packages
foundrykit build --all
# Test all packages
foundrykit test --all
# Lint all packages
foundrykit lint --all
# Run command in specific package
foundrykit dev --package apps/web
Custom Build Pipelines
Advanced Build Configuration
Create complex build pipelines with custom steps.
// foundrykit.config.js
module.exports = {
build: {
pipeline: [
'clean',
'validate',
'compile',
'bundle',
'optimize',
'test',
'deploy'
],
steps: {
clean: {
script: 'rm -rf dist',
description: 'Clean build directory'
},
validate: {
script: 'foundrykit lint && foundrykit type-check',
description: 'Validate code quality'
},
compile: {
script: 'tsc --noEmit',
description: 'TypeScript compilation check'
},
bundle: {
script: 'vite build',
description: 'Bundle application'
},
optimize: {
script: 'foundrykit optimize',
description: 'Optimize bundle'
},
test: {
script: 'foundrykit test --coverage',
description: 'Run tests with coverage'
},
deploy: {
script: 'foundrykit deploy',
description: 'Deploy to production'
}
}
}
}
Custom Build Hooks
Add custom hooks to the build process.
// foundrykit.config.js
module.exports = {
build: {
hooks: {
preBuild: [
'echo "Starting build process..."',
'npm run clean',
'npm run validate'
],
postBuild: [
'echo "Build completed successfully!"',
'npm run analyze',
'npm run notify'
],
onError: [
'echo "Build failed!"',
'npm run notify-error'
]
}
}
}
Advanced Testing
Custom Test Configurations
Configure complex testing setups.
// foundrykit.config.js
module.exports = {
testing: {
frameworks: {
unit: 'jest',
integration: 'playwright',
e2e: 'cypress'
},
environments: {
development: {
unit: { watch: true, coverage: false },
integration: { headless: false },
e2e: { open: true }
},
ci: {
unit: { coverage: true, ci: true },
integration: { headless: true },
e2e: { headless: true }
}
},
parallel: {
enabled: true,
workers: 4
}
}
}
Custom Test Scripts
Create custom test scripts for complex scenarios.
#!/bin/bash
# scripts/test-all.sh
echo "Running all test suites..."
# Run unit tests
echo "Running unit tests..."
foundrykit test --framework jest --coverage
# Run integration tests
echo "Running integration tests..."
foundrykit test --framework playwright --headless
# Run E2E tests
echo "Running E2E tests..."
foundrykit test --framework cypress --headless
# Generate coverage report
echo "Generating coverage report..."
foundrykit coverage --merge --html
echo "All tests completed!"
Deployment Automation
Multi-Environment Deployment
Configure deployment for multiple environments.
// foundrykit.config.js
module.exports = {
deployment: {
environments: {
staging: {
url: 'https://staging.example.com',
build: {
outDir: 'dist-staging',
env: 'staging'
},
deploy: {
provider: 'vercel',
config: './vercel-staging.json'
}
},
production: {
url: 'https://example.com',
build: {
outDir: 'dist-production',
env: 'production'
},
deploy: {
provider: 'vercel',
config: './vercel-production.json'
}
}
},
hooks: {
preDeploy: [
'npm run build',
'npm run test',
'npm run security-scan'
],
postDeploy: [
'npm run health-check',
'npm run notify-success'
]
}
}
}
Custom Deployment Scripts
Create custom deployment scripts.
// scripts/deploy.js
const { execSync } = require('child_process')
const fs = require('fs')
function deploy(environment) {
console.log(`Deploying to ${environment}...`)
// Build for environment
execSync(`foundrykit build --env ${environment}`, { stdio: 'inherit' })
// Run pre-deployment checks
execSync('foundrykit test --ci', { stdio: 'inherit' })
// Deploy based on environment
switch (environment) {
case 'staging':
execSync('vercel --prod', { stdio: 'inherit' })
break
case 'production':
execSync('vercel --prod --confirm', { stdio: 'inherit' })
break
default:
throw new Error(`Unknown environment: ${environment}`)
}
console.log(`Deployment to ${environment} completed!`)
}
// Parse command line arguments
const environment = process.argv[2]
if (!environment) {
console.error('Please specify environment: staging or production')
process.exit(1)
}
deploy(environment)
Performance Optimization
Bundle Analysis
Configure bundle analysis and optimization.
// foundrykit.config.js
module.exports = {
build: {
analyze: {
enabled: true,
output: 'bundle-analysis.html',
threshold: {
size: 500000, // 500KB
chunks: 10
}
},
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
},
treeShaking: true,
minify: true,
sourcemap: false
}
}
}
Performance Monitoring
Set up performance monitoring in your build process.
// scripts/performance-check.js
const fs = require('fs')
const path = require('path')
function checkBundleSize() {
const statsPath = path.join(process.cwd(), 'dist', 'stats.json')
const stats = JSON.parse(fs.readFileSync(statsPath, 'utf8'))
const bundleSize = stats.assets.reduce((total, asset) => {
return total + asset.size
}, 0)
const maxSize = 500000 // 500KB
if (bundleSize > maxSize) {
console.error(`Bundle size ${bundleSize} exceeds limit ${maxSize}`)
process.exit(1)
}
console.log(`Bundle size: ${bundleSize} bytes`)
}
checkBundleSize()
Custom Plugins
Creating CLI Plugins
Create custom plugins to extend CLI functionality.
// plugins/custom-plugin.js
class CustomPlugin {
constructor(config) {
this.config = config
}
apply(compiler) {
// Plugin implementation
compiler.hooks.beforeRun.tap('CustomPlugin', () => {
console.log('Custom plugin: Before run')
})
compiler.hooks.afterRun.tap('CustomPlugin', () => {
console.log('Custom plugin: After run')
})
}
}
module.exports = CustomPlugin
Plugin Configuration
Configure and use custom plugins.
// foundrykit.config.js
module.exports = {
plugins: [
require('./plugins/custom-plugin'),
{
name: 'my-plugin',
config: {
option1: 'value1',
option2: 'value2'
}
}
]
}
Advanced Git Integration
Git Hooks Configuration
Configure advanced Git hooks with the CLI.
// foundrykit.config.js
module.exports = {
git: {
hooks: {
'pre-commit': [
'foundrykit lint --fix',
'foundrykit format --write',
'foundrykit test --watch=false'
],
'pre-push': [
'foundrykit test --coverage',
'foundrykit build',
'foundrykit security-scan'
],
'commit-msg': [
'foundrykit validate-commit'
]
},
conventionalCommits: {
enabled: true,
types: ['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore'],
scopes: ['components', 'hooks', 'utils', 'cli', 'docs']
}
}
}
Automated Release Process
Set up automated releases with semantic versioning.
// scripts/release.js
const { execSync } = require('child_process')
const fs = require('fs')
function createRelease() {
// Get current version
const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'))
const currentVersion = packageJson.version
// Determine next version
const commitType = process.argv[2] || 'patch'
const nextVersion = bumpVersion(currentVersion, commitType)
// Update version
packageJson.version = nextVersion
fs.writeFileSync('package.json', JSON.stringify(packageJson, null, 2))
// Build and test
execSync('foundrykit build', { stdio: 'inherit' })
execSync('foundrykit test --ci', { stdio: 'inherit' })
// Create git tag
execSync(`git add .`, { stdio: 'inherit' })
execSync(`git commit -m "chore: release v${nextVersion}"`, { stdio: 'inherit' })
execSync(`git tag v${nextVersion}`, { stdio: 'inherit' })
execSync(`git push origin main --tags`, { stdio: 'inherit' })
console.log(`Release v${nextVersion} created successfully!`)
}
function bumpVersion(version, type) {
const [major, minor, patch] = version.split('.').map(Number)
switch (type) {
case 'major':
return `${major + 1}.0.0`
case 'minor':
return `${major}.${minor + 1}.0`
case 'patch':
default:
return `${major}.${minor}.${patch + 1}`
}
}
createRelease()
CI/CD Integration
GitHub Actions Configuration
Set up comprehensive CI/CD with GitHub Actions.
# .github/workflows/ci.yml
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linting
run: foundrykit lint
- name: Run tests
run: foundrykit test --coverage
- name: Build application
run: foundrykit build
- name: Upload coverage
uses: codecov/codecov-action@v3
deploy-staging:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/develop'
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- name: Deploy to staging
run: foundrykit deploy staging
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
deploy-production:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- name: Deploy to production
run: foundrykit deploy production
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
Next Steps
- Learn about command reference for detailed usage
- Explore configuration options for customization
- Review best practices for optimal CLI usage