@dscodotco/theme-cli
Version:
A CLI tool for developing Shopify themes
294 lines (240 loc) • 5.79 kB
Markdown
# SimpleDevServer Reference
The `SimpleDevServer` class provides a development server for Shopify themes with live preview capabilities and API endpoints for theme metadata.
## Installation
```typescript
import { SimpleDevServer } from '@dscodotco/theme-cli';
import { ShopifyRenderer } from './renderer';
const server = new SimpleDevServer({
credentials: {
storeName: 'your-store',
apiKey: 'your-api-key',
password: 'your-password'
},
themeId: 123456789,
themeDir: './my-theme',
port: 3000
});
```
## Core Features
### Server Configuration
```typescript
interface DevServerOptions {
credentials: ShopifyCredentials;
themeId: number;
themeDir: string;
port?: number;
host?: string;
https?: boolean;
cors?: boolean;
}
```
### Starting the Server
```typescript
// Start the development server
await server.start();
// Start with custom middleware
server.use(async (ctx, next) => {
console.log(`${ctx.method} ${ctx.url}`);
await next();
});
// Start with HTTPS
await server.start({
https: true,
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
});
```
## API Endpoints
### Theme Metadata
```typescript
// GET /api/theme/metadata
// Returns complete theme metadata
{
"sections": ["header", "footer", "product-grid"],
"templates": {
"index": {
"type": "static",
"sections": ["header", "hero", "footer"]
},
"product": {
"type": "dynamic",
"sections": ["header", "product-details", "footer"]
}
}
}
// GET /api/theme/pages
// Returns list of all available pages
{
"pages": [
{
"path": "/",
"template": "index",
"type": "static"
},
{
"path": "/products/*",
"template": "product",
"type": "dynamic"
}
]
}
// GET /api/theme/page/:path
// Returns metadata for specific page
{
"path": "/products/example-product",
"template": "product",
"type": "dynamic",
"handle": "example-product",
"sections": ["header", "product-details", "footer"]
}
```
### Template Rendering
```typescript
// GET /render/:template
// Renders a template with optional context
const response = await fetch('/render/product', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
handle: 'example-product',
context: {
product: {
title: 'Example Product',
price: '19.99'
}
}
})
});
const html = await response.text();
```
## Development Features
### Live Preview
The development server includes live preview capabilities:
1. **Hot Reload**: Changes to theme files trigger automatic page refresh
2. **Asset Pipeline**: Handles asset compilation and serving
3. **Error Overlay**: Displays compilation and runtime errors in the browser
### Asset Handling
```typescript
// Configure asset handling
server.configureAssets({
compile: true,
minify: process.env.NODE_ENV === 'production',
sourcemaps: process.env.NODE_ENV !== 'production'
});
// Add custom asset processor
server.addAssetProcessor('.scss', async (content, filepath) => {
const result = await sass.renderSync({
data: content,
file: filepath
});
return result.css.toString();
});
```
### Middleware Support
```typescript
// Add custom middleware
server.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
// Add custom route
server.get('/custom-endpoint', async (ctx) => {
ctx.body = { message: 'Custom endpoint' };
});
```
## Error Handling
```typescript
// Global error handler
server.on('error', (error) => {
console.error('Server error:', error);
});
// Template render error handler
server.on('renderError', (error, template) => {
console.error(`Error rendering template ${template}:`, error);
});
// Asset compilation error handler
server.on('assetError', (error, filepath) => {
console.error(`Error compiling asset ${filepath}:`, error);
});
```
## Best Practices
1. **Performance**
- Enable caching in production
- Use compression middleware
- Implement proper asset caching
2. **Security**
- Use HTTPS in production
- Implement proper CORS settings
- Validate user input
3. **Development Workflow**
- Use source maps for better debugging
- Enable hot reload for faster development
- Implement proper error handling
4. **Monitoring**
- Log important events
- Track performance metrics
- Monitor resource usage
## Events
The development server emits several events:
```typescript
server.on('start', () => {
console.log('Server started');
});
server.on('compile', (filepath) => {
console.log('Compiling:', filepath);
});
server.on('reload', () => {
console.log('Page reloaded');
});
server.on('error', (error) => {
console.error('Server error:', error);
});
```
## Configuration Examples
### Basic Development Server
```typescript
const server = new SimpleDevServer({
credentials: {
storeName: 'your-store',
apiKey: 'your-api-key',
password: 'your-password'
},
themeId: 123456789,
themeDir: './my-theme',
port: 3000
});
server.use(compress());
server.use(cors());
await server.start();
```
### Production Server
```typescript
const server = new SimpleDevServer({
credentials: {
storeName: 'your-store',
apiKey: 'your-api-key',
password: 'your-password'
},
themeId: 123456789,
themeDir: './my-theme',
port: process.env.PORT || 3000,
https: true
});
server.configureAssets({
compile: true,
minify: true,
sourcemaps: false,
cache: true
});
server.use(compress());
server.use(helmet());
server.use(rateLimit());
await server.start({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
});
```