Class: Opal::Vite::Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/opal/vite/compiler.rb

Defined Under Namespace

Classes: CompilationError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Compiler

Returns a new instance of Compiler.



10
11
12
13
14
# File 'lib/opal/vite/compiler.rb', line 10

def initialize(options = {})
  @options = options
  @config = options[:config] || Opal::Vite.config
  @include_concerns = options.fetch(:include_concerns, true)
end

Class Method Details

.runtime_codeObject

Get the Opal runtime code



70
71
72
73
74
# File 'lib/opal/vite/compiler.rb', line 70

def self.runtime_code
  builder = Opal::Builder.new
  builder.build('opal')
  builder.to_s
end

Instance Method Details

#compile(source, file_path) ⇒ Object

Compile Ruby source code to JavaScript Returns a hash with :code, :map, and :dependencies



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/opal/vite/compiler.rb', line 18

def compile(source, file_path)
  begin
    # Use Opal::Builder and add the file's directory to load paths
    builder = Opal::Builder.new

    # Add the directory containing the file to load paths
    # This allows require statements to work relative to the file
    file_dir = File.dirname(File.expand_path(file_path))
    builder.append_paths(file_dir)

    # Also add parent directories for common patterns like 'lib/foo'
    parent_dir = File.dirname(file_dir)
    builder.append_paths(parent_dir)

    # Add gem paths from $LOAD_PATH so Opal can find gems
    add_gem_paths(builder)

    builder.build_str(source, file_path)

    result = {
      code: builder.to_s,
      dependencies: extract_dependencies(builder)
    }

    # Extract source map if enabled
    if @config.source_map_enabled
      begin
        source_map = extract_source_map(builder, file_path)
        result[:map] = source_map if source_map
      rescue => e
        # Source map extraction failed, log but don't fail compilation
        warn "Warning: Failed to extract source map for #{file_path}: #{e.message}" if ENV['DEBUG']
      end
    end

    result
  rescue StandardError => e
    raise CompilationError, "Failed to compile #{file_path}: #{e.message}\n#{e.backtrace.first(5).join("\n")}"
  end
end

#compile_file(file_path) ⇒ Object

Compile a Ruby file to JavaScript



60
61
62
63
64
65
66
67
# File 'lib/opal/vite/compiler.rb', line 60

def compile_file(file_path)
  unless File.exist?(file_path)
    raise CompilationError, "File not found: #{file_path}"
  end

  source = File.read(file_path)
  compile(source, file_path)
end