Last active
October 26, 2023 22:26
-
-
Save tobiashm/c1b0b80b2f3616637a64 to your computer and use it in GitHub Desktop.
Add node modules to Rails assets paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Allow Rails to use assets from Node packages | |
package_json = Rails.root.join("package.json") | |
Rails.configuration.watchable_files << package_json | |
Rails.configuration.to_prepare do | |
node_config = JSON.parse(package_json.read) | |
paths = Rails.configuration.assets.paths | |
node_modules = Rails.root.join("node_modules") | |
paths.reject! { |p| p.to_s.start_with?(node_modules.to_s) } | |
node_config["dependencies"].keys.each do |node_module| | |
module_dir = node_modules.join(node_module) | |
fail "Please run `npm install`" unless module_dir.exist? | |
module_config = JSON.parse(module_dir.join("package.json").read) | |
if module_config["main"] | |
main_dir = module_dir.join(module_config["main"]).expand_path.dirname | |
paths << main_dir.to_s unless paths.include?(main_dir.to_s) | |
end | |
if module_config["directories"] && module_config["directories"]["lib"] | |
lib_dir = module_dir.join(module_config["directories"]["lib"]).expand_path | |
paths << lib_dir.to_s if lib_dir != main_dir && !paths.include?(lib_dir.to_s) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment