Skip to content

Commit 7f43c2a

Browse files
committed
Fix(SprocketsRenderer) support Sprockets::Manifest if assets were precompiled
1 parent 3b21569 commit 7f43c2a

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

lib/react/server_rendering/sprockets_renderer.rb

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def initialize(options={})
1111
js_code = CONSOLE_POLYFILL.dup
1212

1313
filenames.each do |filename|
14-
js_code << ::Rails.application.assets[filename].to_s
14+
js_code << get_asset_content(filename)
1515
end
1616

1717
super(options.merge(code: js_code))
@@ -58,6 +58,31 @@ def after_render(component_name, props, prerender_options)
5858
}
5959
})(console.history);
6060
JS
61+
62+
# Given an asset name, return the fully-compiled body of that asset.
63+
#
64+
# Out of the box, it supports a Sprockets::Environment (application.assets)
65+
# and a Sprockets::Manifest (application.assets_manifest), which covers the
66+
# default Rails setups.
67+
#
68+
# Make a `server.js` which has `//= require react-server` and `//= require components`.
69+
# Then add `server` to the precompile list, eg `Rails.application.config.assets.precompile += %w( server.js )`.
70+
#
71+
# In production, react-rails will use the precompiled file.
72+
#
73+
# TODO: what if the assets aren't on the local server (maybe they're on a CDN?)
74+
# Can we check for asset_host configuration here?
75+
def get_asset_content(asset_name)
76+
if ::Rails.application.config.assets.compile
77+
::Rails.application.assets[asset_name].to_s
78+
else
79+
manifest = ::Rails.application.assets_manifest
80+
# Find the corresponding compiled file:
81+
asset_path = manifest.assets[asset_name] || raise("No compiled asset for #{asset_name}, was it precompiled?")
82+
asset_full_path = ::Rails.root.join("public", manifest.directory, asset_path)
83+
File.read(asset_full_path)
84+
end
85+
end
6186
end
6287
end
6388
end

0 commit comments

Comments
 (0)