opal-vite

Core Ruby gem for integrating Opal (Ruby to JavaScript compiler) with Vite. This gem provides the compilation backend for the vite-plugin-opal package.

Features

  • πŸ”¨ Ruby Compilation: Compiles Ruby code to JavaScript using Opal
  • πŸ“Š Dependency Tracking: Tracks require statements and dependencies
  • πŸ—ΊοΈ Source Maps: Generates source maps for debugging
  • βš™οΈ Configuration: Flexible configuration options
  • πŸ”§ CLI: Command-line interface for standalone compilation
  • πŸ”Œ JSON API: JSON-based API for Node.js integration

Installation

Add to your Gemfile:

gem 'opal-vite'

Then run:

bundle install

Requirements

  • Ruby >= 3.0
  • Opal >= 1.8

Usage

As a Library

require 'opal-vite'

# Create a compiler instance
compiler = Opal::Vite::Compiler.new

# Compile Ruby code
source = "class Greeter\n  def greet(name)\n    \"Hello, \#{name}!\"\n  end\nend\n\ngreeter = Greeter.new\nputs greeter.greet(\"World\")\n"

result = compiler.compile(source, 'greeter.rb')

# Access compiled code
puts result[:code]         # JavaScript output
puts result[:map]          # Source map (JSON string)
puts result[:dependencies] # Array of required files

CLI Commands

Compile a File

opal-vite compile app.rb

Compile to File

opal-vite compile app.rb -o app.js

Generate Source Map

opal-vite compile app.rb -o app.js -m

Verbose Output

opal-vite compile app.rb -v

Show Version

opal-vite version

Show Help

opal-vite help

API Reference

Opal::Vite::Compiler

Main compiler class for converting Ruby to JavaScript.

#compile(source, file_path)

Compiles Ruby source code to JavaScript.

Parameters:

  • source (String): Ruby source code
  • file_path (String): Path to the source file

Returns:

  • Hash with :code, :map, and :dependencies keys

.runtime_code

Returns the Opal runtime JavaScript code.

Opal::Vite::Config

Configuration class with attributes:

  • load_paths (Array)
  • source_map_enabled (Boolean)
  • debug (Boolean)

Integration with Vite

This gem works with vite-plugin-opal.

The Vite plugin spawns Ruby processes and uses this gem to compile .rb files.

Examples

Simple Compilation

require 'opal-vite'

compiler = Opal::Vite::Compiler.new
result = compiler.compile('puts "Hello, World!"', 'hello.rb')
puts result[:code]

CLI Usage

# Simple compilation
opal-vite compile app.rb > app.js

# With source map
opal-vite compile app.rb -o app.js -m

# Verbose mode
opal-vite compile app.rb -v

Development

Running Tests

bundle install
bundle exec rspec

License

MIT