Customizable Terminal Emulator Component for Svelte Apps – Svelte Bash

Add terminal interfaces to Svelte apps with Svelte Bash. Includes virtual file system, autoplay, and custom command registration in 4kb.

Svelte Bash is a terminal emulator component that creates interactive command-line interfaces in your Svelte 5+ applications.

It simulates a realistic shell environment complete with a virtual file system, command history, and custom script execution.

You can define custom commands, script autoplay sequences for demos, and configure the prompt display.

Features

Lightweight: Approximately 4kb gzipped with no external dependencies.

📁 Virtual File System: Built-in commands like ls, cd, cat, and pwd operate on a configurable directory structure you define.

🎨 Theme Customization: 4 preset themes (dark, light, dracula, matrix). You can also define custom color schemes through a theme object.

▶️ Autoplay Sequences: Script commands execute automatically in sequence for demonstrations or tutorials.

⌨️ Command History: Navigate previous commands with up and down arrow keys, following standard terminal conventions.

🔧 Custom Commands: Define functions that extend the terminal with project-specific commands.

Use Cases

  • Developer Portfolios: Embeds a working terminal to display projects and skills.
  • Interactive Tutorials: Guides your users through command-line examples on documentation sites.
  • Web-Based Tools: Provides a CLI interface for web applications that process user commands.
  • Landing Page Demos: Runs an automated script to showcase features without user input.

Use Cases

  • Developer Portfolios: Display your command-line skills through an interactive terminal that showcases projects and experience.
  • Documentation Sites: Walk users through CLI workflows with autoplay sequences that demonstrate installation steps and usage patterns.
  • Web-Based Tools: Build browser applications that need terminal-style input for configuration or command execution.
  • Educational Platforms: Create interactive tutorials that teach shell commands and file system navigation in a safe environment.

How to Use It

1. Install the package through npm in your Svelte project.

npm install svelte-bash

2. Import the Terminal component and define a file structure object. The structure represents your virtual file system, where keys are file or directory names and values are either strings (file contents) or nested objects (directories).

Users can now run ls to see files, cd docs to navigate directories, and cat readme.txt to read file contents.

<script>
  import { Terminal } from 'svelte-bash';
  const files = {
    'index.html': '<html><body>Hello</body></html>',
    'styles.css': 'body { margin: 0; }',
    'docs': {
      'readme.txt': 'Project documentation',
      'guide.txt': 'Setup instructions'
    }
  };
</script>
<Terminal 
  structure={files}
  user="developer"
  machine="localhost"
  style="height: 400px; width: 100%;"
/>

2. Extend the terminal with custom commands specific to your application. Pass a commands object where each key is the command name and the value is a function that returns output.

Functions can accept arguments from the command line and support asynchronous operations for API calls or other async tasks.

<script>
  import { Terminal } from 'svelte-bash';
  const customCommands = {
    greet: (args) => {
      const name = args[0] || 'Developer';
      return `Hello, ${name}!`;
    },
    date: () => {
      return new Date().toLocaleString();
    },
    fetch: async (args) => {
      const url = args[0];
      const response = await fetch(url);
      const data = await response.json();
      return JSON.stringify(data, null, 2);
    }
  };
</script>
<Terminal commands={customCommands} />

3. Create demonstration sequences where commands execute automatically. Define an array of autoplay items with command text and optional output.

The terminal types each command with realistic timing and executes them in order. Set readonly to true when you want to prevent user input during demonstrations.

<script>
  import { Terminal } from 'svelte-bash';
  const demoSequence = [
    { 
      command: "ls",
      delay: 500
    },
    { 
      command: "cd src",
      delay: 800
    },
    { 
      command: "cat main.js",
      delay: 1000
    }
  ];
</script>
<Terminal 
  autoplay={demoSequence}
  readonly={true}
/>

4. Apply preset themes by passing a string, or define custom colors through a theme object. Available themes:

  • dark (default)
  • light
  • dracula
  • matrix
<script>
  import { Terminal } from 'svelte-bash';
  // Using a preset
  const preset = 'dracula';
  // Custom theme
  const customTheme = {
    background: '#0d1117',
    foreground: '#c9d1d9',
    prompt: '#58a6ff',
    cursor: '#f0883e',
    error: '#f85149'
  };
</script>
<Terminal theme={preset} />
<!-- or -->
<Terminal theme={customTheme} />

5. Display a welcome text when the terminal initializes.

<Terminal 
  welcomeMessage={[
    "Welcome to Svelte Bash v1.0",
    "Type 'help' for available commands",
    ""
  ]}
/>

6. All available component props to customize your terminal.

PropertyTypeDefaultDescription
structureFileStructure{}Object defining the virtual file system structure where keys are names and values are contents or nested objects.
commandsRecord<string, Function>{}Custom command handlers that extend built-in functionality.
themestring | Theme'dark'Preset theme name or object with custom color values.
userstring'user'Username displayed in the command prompt.
machinestring'machine'Machine name displayed in the command prompt.
welcomeMessagestring | string[][]Text or lines shown when terminal initializes.
autoplayAutoplayItem[]undefinedCommands that execute automatically in sequence.
readonlybooleanfalseWhen true, disables user input for demonstration mode.
stylestringundefinedInline CSS styles applied to the terminal container.

Related Resources

  • xterm.js: A terminal component that works with React, Angular, and Vue through framework-specific wrappers.
  • Terminal CSS: A classless CSS framework that styles HTML elements to look like terminal windows.
  • Terminal Emulator: A simple jQuery-based terminal emulator that makes it easy to create a command line interpreter for your website or web application.

FAQs

Q: Can I use Svelte Bash without Tailwind CSS?
A: Yes. Version 1.0.1 and later use pure vanilla CSS internally.

Q: How do I persist command history between sessions?
A: The component stores history in memory during the current session. You need to implement localStorage or another storage mechanism to save history across page reloads.

Q: Can custom commands call external APIs?
A: Yes. Define async functions in your commands object and the terminal handles the promise resolution before displaying output.

Q: Does the virtual file system support nested directories?
A: Yes. Create nested objects in your structure definition and the cd command navigates through multiple directory levels.

Q: How do I customize the prompt format?
A: Set the user and machine props to change the displayed names. The current format is user@machine:path$ and cannot be modified beyond these values.

Yusuf Cengiz

Yusuf Cengiz

Front-end developer

Leave a Reply

Your email address will not be published. Required fields are marked *