@berhalak/preview
Version:
A CLI tool to preview HTML, JS, and TS files in an Electron window with auto-reload
264 lines (208 loc) โข 6.29 kB
Markdown
# ๐ Preview CLI (coded mostly by AI)
A powerful CLI tool that instantly opens and previews `.html`, `.js`, and `.ts` files in an Electron window with automatic hot-reloading.
## โจ Features
- ๐ **Instant Preview** - Open any HTML, JavaScript, or TypeScript file in seconds
- ๐ **Auto-Reload** - Automatically reloads when files change
- ๐ฆ **TypeScript Support** - Automatic transpilation using esbuild
- ๐ฅ **Hot Module Reloading** - Fast feedback loop for rapid development
- ๐ฏ **Simple CLI** - Just one command to preview any file
- โจ **Reload Toast** - Visual feedback when files reload
- ๐๏ธ **Menu API** - Customize application menus from your scripts
## ๐ฆ Installation
### Local Installation
```bash
npm install
```
### Global Installation (Recommended)
```bash
npm install -g .
```
After global installation, the `preview` command will be available system-wide.
## ๐ Usage
### Basic Usage
```bash
preview <path-to-file>
```
### Examples
```bash
# Preview an HTML file
preview index.html
# Preview a JavaScript file
preview app.js
# Preview a TypeScript file (auto-transpiles)
preview demo.ts
```
## ๐ฏ How It Works
### HTML Files
- Loads directly using Electron's `loadFile()`
- Watches for changes and reloads automatically
### JavaScript Files
- Wraps in a minimal HTML template
- Loads the script and executes it
- Watches for changes and reloads
### TypeScript Files
- Transpiles to JavaScript using **esbuild**
- Outputs to system temp directory (`os.tmpdir()/preview-electron/`)
- Watches source files and rebuilds on changes
- Auto-reloads after successful transpilation
## ๐ Project Structure
```
preview/
โโโ bin/
โ โโโ preview.js # CLI entry point with shebang
โโโ src/
โ โโโ main.js # Electron main process
โ โโโ previewServer.js # File watcher & esbuild transpiler
โ โโโ renderer.html # HTML wrapper template for JS/TS
โโโ package.json
โโโ tsconfig.json
โโโ README.md
```
## ๐ ๏ธ Technical Details
### Dependencies
- **electron** - Cross-platform desktop app framework
- **esbuild** - Fast TypeScript/JavaScript bundler
- **chokidar** - Efficient file watcher
### Window Configuration
- Default size: 800ร600 pixels
- Resizable window
- DevTools open by default
- Node.js integration enabled (`nodeIntegration: true`)
- Context isolation disabled for direct Node.js access
### File Watching
The tool watches for changes in:
- The main file being previewed
- CSS files in the same directory
- Related TypeScript/JavaScript files
### Temporary Files
- Compiled TypeScript outputs are saved to system temp directory
- Location: `os.tmpdir()/preview-electron/<filename>/`
- Automatically cleaned up when the app closes
## ๐จ Example Files
### Example TypeScript (`demo.ts`)
```typescript
document.body.innerHTML = `
<div style="padding: 40px; text-align: center;">
<h1>Hello from TypeScript! ๐</h1>
<p>Edit this file and watch it reload automatically.</p>
<p>Current time: ${new Date().toLocaleTimeString()}</p>
</div>
`;
setInterval(() => {
const timeEl = document.querySelector('p:last-child');
if (timeEl) {
timeEl.textContent = `Current time: ${new Date().toLocaleTimeString()}`;
}
}, 1000);
```
### Example JavaScript (`demo.js`)
```javascript
document.body.innerHTML = `
<div style="padding: 40px; text-align: center;">
<h1>Hello from JavaScript! ๐</h1>
<p>Changes auto-reload instantly.</p>
</div>
`;
```
### Example HTML (`demo.html`)
```html
<!DOCTYPE html>
<html>
<head>
<title>Preview Demo</title>
<style>
body { padding: 40px; font-family: sans-serif; }
</style>
</head>
<body>
<h1>Hello from HTML! ๐</h1>
<p>Edit and save to see changes instantly.</p>
</body>
</html>
```
## ๐๏ธ Preview API
When running JavaScript or TypeScript files, a global `PreviewAPI` object is available to interact with the preview window.
### Menu Customization
```typescript
// Set a complete custom menu
PreviewAPI.setMenu([
{
label: 'File',
submenu: [
{ label: 'Action 1', id: 'action1', accelerator: 'CmdOrCtrl+1' },
{ label: 'Action 2', id: 'action2', accelerator: 'CmdOrCtrl+2' },
{ type: 'separator' },
{ label: 'Quit', role: 'quit' }
]
},
{
label: 'View',
submenu: [
{ label: 'Reload', role: 'reload' },
{ label: 'Toggle DevTools', role: 'toggleDevTools' }
]
}
]);
// Add a single menu item
PreviewAPI.addMenuItem('Custom', [
{ label: 'Say Hello', id: 'hello', accelerator: 'CmdOrCtrl+H' },
{ label: 'Open DevTools', role: 'toggleDevTools' }
]);
// Handle menu actions
PreviewAPI.onMenuAction('action1', () => {
console.log('Action 1 triggered!');
alert('You clicked Action 1');
});
PreviewAPI.onMenuAction('hello', () => {
console.log('Hello from menu!');
});
```
### Available Roles
Electron provides built-in menu roles:
- `quit` - Quit the application
- `reload` - Reload the window
- `toggleDevTools` - Toggle developer tools
- `resetZoom`, `zoomIn`, `zoomOut` - Zoom controls
- And many more (see Electron documentation)
### Try it!
Run the menu demo to see it in action:
```bash
preview examples/menu-demo.ts
```
## ๐งช Testing
```bash
# Test with a demo file
npm test
# Or manually test with your own files
preview examples/demo.html
preview examples/demo.js
preview examples/demo.ts
```
## ๐ฏ Development Workflow
1. Create your HTML/JS/TS file
2. Run `preview <filename>`
3. Edit the file in your favorite editor
4. Save - watch it reload automatically! โจ
5. See the "Reloaded โจ" toast notification
## ๐ง Troubleshooting
### Command not found
If `preview` command is not found after global installation:
```bash
npm link
```
### File not found
Make sure to provide the correct path to the file:
```bash
# Use absolute path
preview /full/path/to/file.ts
# Or relative path from current directory
preview ./src/app.ts
```
### TypeScript compilation errors
Check the terminal output for esbuild errors. The preview will not reload if compilation fails.
## ๐ License
MIT
## ๐ค Contributing
Contributions are welcome! Feel free to open issues or submit pull requests.
---
Built with โค๏ธ using Electron, esbuild, and chokidar