module Webpack::Rails::Helper

Asset path helpers for use with webpack

Public Instance Methods

webpack_asset_paths(source, extension: nil, ignore_missing: false) click to toggle source

Return asset paths for a particular webpack entry point.

Response may either be full URLs (eg localhost/…) if the dev server is in use or a host-relative URl (eg /webpack/…) if assets are precompiled.

Will raise an error if our manifest can't be found or the entry point does not exist.

# File lib/webpack/rails/helper.rb, line 15
def webpack_asset_paths(source, extension: nil, ignore_missing: false)
  return "" unless source.present?

  begin
    if ::Rails.configuration.webpack.manifest_type == "manifest"
      extension = "js" if extension.nil?
      paths = Webpack::Rails::Manifest.manifest_asset_paths(source + "." + extension)
    elsif ::Rails.configuration.webpack.manifest_type == "stats"
      paths = Webpack::Rails::Manifest.asset_paths(source)
      paths = paths.select { |p| p.ends_with? ".#{extension}" } if extension
    end
  rescue Webpack::Rails::Manifest::EntryPointMissingError => e
    # puts "webpack asset missing in manifest: #{source}"
    raise e unless ignore_missing
  end

  port = ::Rails.configuration.webpack.dev_server.port
  protocol = ::Rails.configuration.webpack.dev_server.https ? 'https' : 'http'

  host = ::Rails.configuration.webpack.dev_server.host
  host = instance_eval(&host) if host.respond_to?(:call)

  if ::Rails.configuration.webpack.dev_server.enabled && ::Rails.configuration.webpack.manifest_type == "stats"
    paths.map! do |p|
      "#{protocol}://#{host}:#{port}#{p}"
    end
  end

  paths
end