Skip to main content

Shakapacker API Reference

Ruby API Reference​

This document provides a comprehensive reference for Shakapacker's public Ruby API. For JavaScript bundler configuration, see the Configuration Guide.

Table of Contents​

Overview​

Shakapacker provides a Ruby API for integrating webpack/rspack with Rails applications. The API is divided into several key areas:

  • Configuration: Access to config/shakapacker.yml settings
  • View Helpers: Rails helpers for rendering script/link tags
  • Manifest: Asset lookup and resolution
  • Compilation: Programmatic asset compilation
  • Dev Server: Development server status and management

What's Public API?​

Methods and classes marked with @api public in the source code are considered stable public API. Other methods may change between minor versions.

Main Module: Shakapacker​

The Shakapacker module provides singleton-style access to all major functionality.

Configuration Access​

Quick Examples​

# Get the configuration object
Shakapacker.config
# => #<Shakapacker::Configuration>

# Access configuration values
Shakapacker.config.source_path
# => #<Pathname:/path/to/app/javascript>

Shakapacker.config.public_output_path
# => #<Pathname:/path/to/public/packs>

Compilation​

# Compile all packs
Shakapacker.compile
# => true

# Check if compilation is needed
Shakapacker.compiler.stale?
# => false

# Get compiler output
Shakapacker.compiler.compile

Manifest Lookup​

# Look up compiled asset path
Shakapacker.manifest.lookup("application.js")
# => "/packs/application-abc123.js"

# Look up with error if not found
Shakapacker.manifest.lookup!("application.js")
# => "/packs/application-abc123.js" (or raises Shakapacker::Manifest::MissingEntryError)

Dev Server Status​

# Check if dev server is running
Shakapacker.dev_server.running?
# => true

# Get dev server host
Shakapacker.dev_server.host
# => "localhost"

# Get dev server port
Shakapacker.dev_server.port
# => 3035

Environment Management​

# Get current environment
Shakapacker.env
# => #<ActiveSupport::StringInquirer "development">

# Temporarily use different NODE_ENV
Shakapacker.with_node_env("production") do
Shakapacker.compile
end

Logging​

# Access logger
Shakapacker.logger
# => #<Logger>

# Redirect to STDOUT temporarily
Shakapacker.ensure_log_goes_to_stdout do
Shakapacker.compile
end

Configuration API​

The Shakapacker::Configuration class provides access to all settings from config/shakapacker.yml.

Accessing Configuration Data​

config = Shakapacker.config

# Get raw configuration hash (symbol-keyed)
config.data
# => { source_path: "app/javascript", ... }

# Access specific values
config.data[:source_path]
# => "app/javascript"

See Also: Configuration Guide for all available options.

Path Configuration​

# Source paths
config.source_path # => #<Pathname:/app/app/javascript>
config.source_entry_path # => #<Pathname:/app/app/javascript/packs>
config.additional_paths # => ["app/assets", ...]

# Output paths
config.public_path # => #<Pathname:/app/public>
config.public_output_path # => #<Pathname:/app/public/packs>
config.public_manifest_path # => #<Pathname:/app/public/packs/manifest.json>

Bundler Detection​

# Check which bundler is configured
config.webpack? # => true
config.rspack? # => false
config.bundler # => "webpack"

# Get bundler config path
config.assets_bundler_config_path
# => "config/webpack"

Compilation Settings​

config.compile?              # => true (auto-compile enabled?)
config.cache_manifest? # => false
config.javascript_transpiler # => "swc"
config.webpack_compile_flags # => ["--progress", "--fail-on-warnings"]
config.nested_entries? # => false

Dev Server Configuration​

dev_server = config.dev_server
dev_server[:host] # => "localhost"
dev_server[:port] # => 3035
dev_server[:hmr] # => true
dev_server[:server] # => "http"

View Helpers​

Shakapacker provides Rails view helpers in the Shakapacker::Helper module, automatically included in ActionView. You can also consult the source documentation in helper.rb.

For styles or static assets to be available in a view, link them from a pack or entry file. Otherwise, webpack/rspack will not know to package those files.

View Helpers javascript_pack_tag and stylesheet_pack_tag​

JavaScript Pack Tag​

# Basic usage
<%= javascript_pack_tag 'application' %>
# => <script src="/packs/application-abc123.js" defer></script>

# Multiple packs (handles chunk deduplication)
<%= javascript_pack_tag 'calendar', 'map' %>

# Custom attributes
<%= javascript_pack_tag 'application', 'data-turbo-track': 'reload' %>

# Async loading
<%= javascript_pack_tag 'application', async: true %>

# Disable defer
<%= javascript_pack_tag 'application', defer: false %>

# Early hints configuration
<%= javascript_pack_tag 'application', early_hints: 'preload' %>
<%= javascript_pack_tag 'application', early_hints: false %>

Important: Call javascript_pack_tag only once per page to avoid duplicate chunks.

Stylesheet Pack Tag​

# Basic usage
<%= stylesheet_pack_tag 'application' %>
# => <link rel="stylesheet" href="/packs/application-abc123.css">

# Multiple packs with attributes
<%= stylesheet_pack_tag 'application', 'calendar', media: 'screen' %>

# Early hints
<%= stylesheet_pack_tag 'application', early_hints: 'preload' %>

View Helper append_javascript_pack_tag, prepend_javascript_pack_tag and append_stylesheet_pack_tag​

Dynamic Pack Loading​

# In view or partial - queue packs
<% append_javascript_pack_tag 'calendar' %>
<% append_stylesheet_pack_tag 'calendar' %>

# Prepend to queue
<% prepend_javascript_pack_tag 'critical' %>

# In layout - render all queued packs
<%= javascript_pack_tag 'application' %>
<%= stylesheet_pack_tag 'application' %>

Asset Helpers​

View Helper: asset_pack_path​

# Get pack path
<%= asset_pack_path 'logo.svg' %>
# => "/packs/logo-abc123.svg"

# Get pack URL
<%= asset_pack_url 'logo.svg' %>
# => "https://cdn.example.com/packs/logo-abc123.svg"

View Helper: image_pack_tag​

# Image pack tag
<%= image_pack_tag 'logo.png', size: '16x10', alt: 'Logo' %>
# => <img src="/packs/logo-abc123.png" width="16" height="10" alt="Logo">

# With srcset
<%= image_pack_tag 'photo.png', srcset: { 'photo-2x.png' => '2x' } %>

View Helper: favicon_pack_tag​

# Favicon
<%= favicon_pack_tag 'icon.png', rel: 'apple-touch-icon' %>

View Helper: preload_pack_asset​

# Preload asset
<%= preload_pack_asset 'fonts/custom.woff2' %>

If you use server-side rendering of JavaScript with dynamic code-splitting, as is often done with extensions like React on Rails, your JavaScript should create the link prefetch HTML tags. In that case, you usually do not need to use asset_pack_path for those split assets.

Manifest API​

The Shakapacker::Manifest class handles asset lookup from the compiled manifest.

Basic Lookup​

manifest = Shakapacker.manifest

# Look up an asset (returns nil if not found)
manifest.lookup("application.js")
# => "/packs/application-abc123.js"

# Look up with error on missing
manifest.lookup!("application.js")
# => "/packs/application-abc123.js" (raises if missing)

Lookup with Type​

# Lookup stylesheets
manifest.lookup("application.css")
# => "/packs/application-abc123.css"

# Lookup images
manifest.lookup("logo.svg")
# => "/packs/static/logo-abc123.svg"

Refreshing Manifest Data​

# Refresh manifest from disk
manifest.refresh
# => { "application.js" => "/packs/application-abc123.js", ... }

Dev Server API​

The Shakapacker::DevServer class provides status and configuration for the development server.

Status Checking​

dev_server = Shakapacker.dev_server

# Check if running
dev_server.running?
# => true

# Get connection info
dev_server.protocol
# => "http"

dev_server.host_with_port
# => "localhost:3035"

Configuration​

dev_server.host
# => "localhost"

dev_server.port
# => 3035

dev_server.server
# => "http"

dev_server.hmr?
# => true

Compiler API​

The Shakapacker::Compiler class handles compilation of webpack/rspack assets.

Compilation​

compiler = Shakapacker.compiler

# Compile all packs
compiler.compile
# => true

# Check if compilation needed
compiler.stale?
# => false

# Check if assets are current
compiler.fresh?
# => true

Advanced Usage​

Multiple Shakapacker Instances​

For advanced scenarios like Rails engines with separate webpack configs:

# Create custom instance
custom_instance = Shakapacker::Instance.new(
root_path: Rails.root,
config_path: Rails.root.join("config/custom_shakapacker.yml")
)

# Use in view helper
def current_shakapacker_instance
@custom_instance ||= Shakapacker::Instance.new(...)
end

Testing​

# In tests, you can stub the instance
RSpec.describe "my feature" do
let(:mock_manifest) { instance_double(Shakapacker::Manifest) }
let(:mock_instance) { instance_double(Shakapacker::Instance, manifest: mock_manifest) }

before do
allow(Shakapacker).to receive(:instance).and_return(mock_instance)
end
end

Programmatic Configuration Access​

# Access raw configuration for custom tooling
config_data = Shakapacker.config.data

# Use in custom rake task
namespace :assets do
task :analyze do
config = Shakapacker.config
puts "Source: #{config.source_path}"
puts "Output: #{config.public_output_path}"
puts "Bundler: #{config.bundler}"
end
end

Custom Webpack Configuration​

Access Shakapacker config from your webpack config:

// config/webpack/webpack.config.js
const { generateWebpackConfig } = require("shakapacker")

// The shakapacker.yml is automatically loaded
const config = generateWebpackConfig()

console.log(config.output.path) // Uses public_output_path from shakapacker.yml

Environment Variables​

Shakapacker respects these environment variables:

VariablePurposeExample
SHAKAPACKER_CONFIGCustom config file path/custom/shakapacker.yml
SHAKAPACKER_PRECOMPILEEnable/disable precompilationfalse
SHAKAPACKER_ASSET_HOSTCDN hostnamehttps://cdn.example.com
SHAKAPACKER_ASSETS_BUNDLEROverride bundler selectionrspack
RAILS_ENVRails environmentproduction
NODE_ENVNode environmentproduction

Error Handling​

# Manifest lookup errors
begin
path = Shakapacker.manifest.lookup!("missing.js")
rescue Shakapacker::Manifest::MissingEntryError => e
Rails.logger.error "Missing pack: #{e.message}"
end

# Compilation returns a boolean status
unless Shakapacker.compiler.compile
Rails.logger.error "Compilation failed. Check preceding Shakapacker output."
end

# Accessing an unknown config key raises KeyError
begin
Shakapacker.config.fetch(:unknown_key)
rescue KeyError => e
Rails.logger.error "Invalid config lookup: #{e.message}"
end

Deprecations​

Shakapacker follows semantic versioning. Deprecated methods will:

  1. Issue warnings in the current major version
  2. Be removed in the next major version

Check the CHANGELOG for deprecation notices.

See Also​

Generating Full API Documentation​

For complete API documentation with all methods and parameters:

# Using YARD (recommended)
gem install yard
yard doc
yard server # View at http://localhost:8808

# Using RDoc
rdoc lib/
open doc/index.html

The generated documentation includes all public and private methods with detailed parameter descriptions.

Type Signatures with RBS​

Shakapacker includes RBS type signatures for public Ruby APIs, enabling static type checking and improved IDE support.

Benefits:

  • IDE autocomplete with method signatures and parameter hints.
  • Static type checking with tools such as Steep or TypeProf.
  • Machine-readable API documentation.
  • Safer refactoring across Shakapacker API calls.

RBS signatures are in the sig/ directory and included with the gem:

sig/
├── shakapacker.rbs
└── shakapacker/
├── configuration.rbs
├── helper.rbs
├── manifest.rbs
├── compiler.rbs
├── dev_server.rbs
└── ...

Example Steep configuration:

# Steepfile
target :app do
signature "sig"
check "app"
library "shakapacker"
end

Example type-checked usage:

config = Shakapacker.config
config.source_path
config.webpack?

# Type checkers can report this as an undefined method:
config.invalid_method