I have opened an issue in the importmap-rails gem github repository here about this but thought I'd throw the question out here in case anyone might have a workaround
This is what I have discovered so far
A new engine with Rails 7 alpha 2 or Rails 7.0, generated using rails plugin new custom_page --mountable --full generates a new engine that includes the importmap-rails gem in the bundled gems but there is no ability to use it. Adding spec.add_dependency 'importmap-rails' to the enginename.gemspec makes no difference, nor does adding a require importmap-rails to engine.rb. There is no importmap executable in the bin directory.
A call to bundle info importmap-rails
Produces a promising result showing that the gem is installed by default
* importmap-rails (0.8.1)
Summary: Use ESM with importmap to manage modern JavaScript in Rails without transpiling or bundling.
Homepage: https://github.com/rails/importmap-rails
Source Code: https://github.com/rails/importmap-rails
Path: /home/jamie/.rvm/gems/ruby-3.0.0#custom_page/gems/importmap-rails-0.8.1
A call to rails --tasks shows
rails app:importmap:install # Setup Importmap for the app
But I believe this is coming from the test application generated by the --full option rather than being available to the rails command for the engine.
I was expecting to see the same without app: prefix
A call to this task resolves to a template error as shown
rails app:importmap:install
Don't know how to build task 'app:template' (See the list of available
tasks with rails --tasks) Did you mean? app:tmp:create
If there is a workaround solution to this I'd be grateful to hear it and I'm sure others will too. The reason for me wanting this is that I totally failed to introduced webpacker in a rails 6.1.4 engine and I was hoping this was going to be my, much improved, solution
You don't need to use the install task to set up importmaps. All it does is a few copy paste operations and it doesn't really help with the engine set up anyway.
Add importmaps to engine's gemspec file:
# my_engine/my_engine.gemspec
spec.add_dependency "importmap-rails"
Update engine.rb:
# my_engine/lib/my_engine/engine.rb
require "importmap-rails"
module MyEngine
class Engine < ::Rails::Engine
isolate_namespace MyEngine
initializer "my-engine.importmap", before: "importmap" do |app|
# NOTE: this will add pins from this engine to the main app
# https://github.com/rails/importmap-rails#composing-import-maps
app.config.importmap.paths << root.join("config/importmap.rb")
# NOTE: something about cache; I did not look into it.
# https://github.com/rails/importmap-rails#sweeping-the-cache-in-development-and-test
app.config.importmap.cache_sweepers << root.join("app/assets/javascripts")
end
# NOTE: add engine manifest to precompile assets in production
initializer "my-engine.assets" do |app|
app.config.assets.precompile += %w[my_engine_manifest]
end
end
end
Update assets manifest:
# my_engine/app/assets/config/my_engine_manifest.js
//= link_tree ../javascripts/my_engine .js
Add javascript entry point for our engine, if needed. Pins will be available without this file.
# my_engine/app/assets/javascripts/my_engine/application.js
// do some javascript
document.querySelector("h1").innerText = "hi, i'm your engine";
console.log("hi, again");
Update engine's layout:
# my_engine/app/views/layouts/my_engine/application.html.erb
<!DOCTYPE html>
<html>
<head>
<!--
NOTE: This loads/imports main app `application.js` and all the pins from
the main app and from the engine (because we set it up in the engine.rb).
-->
<%= javascript_importmap_tags %>
<!--
NOTE: To add engine's javascript functionality we have to load the
entrypoint here or `import` it in the main app `application.js`
-->
<%= javascript_import_module_tag "my_engine/application" %>
</head>
<body> <%= yield %> </body>
</html>
Create importmap.rb and pin my_engine/application, this name has to match with javascript_import_module_tag. It cannot clash with any other name in the main app, so you can't just use application:
# my_engine/config/importmap.rb
# NOTE: this pin works because `my_engine/app/assets/javascripts
# is in the `Rails.application.config.assets.paths`
pin "my_engine/application"
Some extras to test the setup:
# config/routes.rb
Rails.application.routes.draw do
mount MyEngine::Engine => "/"
end
# my_engine/config/routes.rb
MyEngine::Engine.routes.draw do
get "home", to: "homes#index"
end
# my_engine/app/controllers/my_engine/homes_controller.rb
module MyEngine
class HomesController < ApplicationController
def index; end
end
end
# my_engine/app/views/my_engine/homes/index.html.erb
<h1>Home</h1>
At this point you should have this in your rendered layout's <head> tag, among other things:
<script type="importmap" data-turbo-track="reload">{
"imports": {
"application": "/assets/application-66ce7505c61e3e4910ff16e7c220e1fbfb39251cd82e4bab8d325b3aae987cf9.js",
"my_engine/application": "/assets/my_engine/application-31ce493e8376b4c20703a50f38d419ae309ffe410b7ab7fec47440e02eef08a8.js",
}
}</script>
<script type="module">import "application"</script>
<script type="module">import "my_engine/application"</script>
H1 tag should change to <h1>hi, i'm your engine</h1> on reload.
Additional importmaps can be added manually with https://generator.jspm.io/.
For bonus points, bin/importmap can be customized to work inside the engine. Create a new importmap file inside bin directory.
# my_engine/bin/importmap
#!/usr/bin/env ruby
# NOTE: don't forget to `chmod u+x bin/importmap` to make it executable.
# make sure we are loading the correct versions of things
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"])
# NOTE: importmap requires some rails goodness that we don't have in the engine,
# because we don't have `config/application.rb` that loads the environment.
require "rails"
# importmap-rails is not loaded automatically
require "importmap-rails"
# the actual command runner
require "importmap/commands"
Run from inside the engine directory:
$ bin/importmap pin react
Pinning "react" to https://ga.jspm.io/npm:react#18.1.0/index.js
$ cat config/importmap.rb
pin "my_engine/application"
pin "react", to: "https://ga.jspm.io/npm:react#18.1.0/index.js"
I haven't tested it too much, so any feedback would be welcome. Restart the server if something doesn't show up, I don't know how reloading behaves with all this.
I fall back to the old school Javascript include in the html.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
Well it definitely works on all browser instead of figuring out if the browser supports the feature that I might use later.
I have full control which page to put too... but that might not be what you want...
I keep receiving this error message from the console when visiting my website:
font from origin 'https://xxx.cloudfront.net' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.example.com' is therefore not allowed access.
I've tried everything:
I've installed the font_assets gem
configured the application.rb file
config.font_assets.origin = 'http://example.com'
Whitelisted Headers on Cloudfront as explained in this article to
Access-Control-Allow-Origin
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Max-Age
But nothing, zero, nada.
I'm using Rails 4.1 on Heroku.
This was an incredibly difficult issue to deal with, for two reasons:
The fact that CloudFront is mirroring our Rails app’s response headers requires you to twist your mind around. The CORS protocol is hard enough to understand as it is, but now you have to follow it at two levels: between the browser and CloudFront (when our Rails app uses it as a CDN), and between the browser and our Rails app (when some malicious site wants to abuse us).
CORS is really about a dialog between the browser and the 3rd-party resources a web page wants to access. (In our use-case, that’s the CloudFront CDN, serving assets for our app.) But since CloudFront gets its Access-Control response headers from our app, our app needs to serve those headers as if it is CloudFront talking, and simultaneously not grant permissions that would expose itself to the type of abuse that led to the Same-Origin Policy / CORS being developed in the first place. In particular, we should not grant * access to * resources on our site.
I found so much outdated information out there -- an endless line of blog posts and SO threads. CloudFront has improved its CORS support significantly since many of those posts, although it is still not perfect. (CORS should really be handled out-of-the-box.) And the gems themselves have evolved.
My setup: Rails 4.1.15 running on Heroku, with assets served from CloudFront. My app responds to both http and https, on both "www." and the zone apex, without doing any redirection.
I looked briefly at the font_assets gem mentioned in the question, but quickly dropped it in favor of rack-cors, which seemed more on point. I did not want to simply open up all origins and all paths, as that would defeat the point of CORS and the security of the Same-Origin Policy, so I needed to be able to specify the few origins I would allow. Finally, I personally favor configuring Rails via individual config/initializers/*.rb files rather than editing the standard config files (like config.ru or config/application.rb) Putting all that together, here is my solution, which I believe is the best available, as of 2016-04-16:
Gemfile
gem "rack-cors"
The rack-cors gem implements the CORS protocol in a Rack middleware.
In addition to setting Access-Control-Allow-Origin and related headers on approved origins, it adds a Vary: Origin response header, directing CloudFront to cache the responses (including the response headers) for each origin separately. This is crucial when our site is accessible via multiple origins (e.g. via both http and https, and via both "www." and the bare domain)
config/initializers/rack-cors.rb
## Configure Rack CORS Middleware, so that CloudFront can serve our assets.
## See https://github.com/cyu/rack-cors
if defined? Rack::Cors
Rails.configuration.middleware.insert_before 0, Rack::Cors do
allow do
origins %w[
https://example.com
http://example.com
https://www.example.com
http://www.example.com
https://example-staging.herokuapp.com
http://example-staging.herokuapp.com
]
resource '/assets/*'
end
end
end
This tells the browser that it may access resources on our Rails app (and by extension, on CloudFront, since it is mirroring us) only on behalf of our Rails app (and not on behalf of malicious-site.com) and only for /assets/ urls (and not for our controllers). In other words, allow CloudFront to serve assets but don't open the door any more than we have to.
Notes:
I tried inserting this after rack-timeout instead of at the head of the middleware chain.
It worked on dev but was not kicking in on Heroku, despite
having the same middleware (other than Honeybadger).
The origins list could also be done as Regexps.
Be careful to anchor patterns at the end-of-string.
origins [
/\Ahttps?:\/\/(www\.)?example\.com\z/,
/\Ahttps?:\/\/example-staging\.herokuapp\.com\z/
]
but I think it’s easier just to read literal strings.
Configure CloudFront to pass the browser's Origin request header on to our Rails app.
Strangely, it appears that CloudFront forwards the Origin header from the browser to our Rails app regardless whether we add it here, but that CloudFront honors our app’s Vary: Origin caching directive only if Origin is explicitly added to the headers whitelist (as of April 2016).
The request header whitelist is kind of buried.
If the distribution already exists, you can find it at:
https://console.aws.amazon.com/cloudfront/home#distributions
select the distribution
click Distribution Settings
go to the Behaviors tab
select the behavior (there will probably be only one)
Click Edit
Forward Headers: Whitelist
Whitelist Headers: Select Origin and click Add >>
If you have not created the distribution yet, create it at:
https://console.aws.amazon.com/cloudfront/home#distributions
Click Create Distribution
(For the sake of completeness and reproducibility, I'm listing all the settings I changed from the defaults, however the Whitelist settings are the only ones that are relevant to this discussion)
Delivery Method: Web (not RTMP)
Origin Settings
Origin Domain Name: example.com
Origin SSL Protocols: TLSv1.2 ONLY
Origin Protocol Policy: HTTPS only
Default Cache Behavior Settings
Viewer Protocol Policy: Redirect HTTP to HTTPS
Forward Headers: Whitelist
Whitelist Headers: Select Origin and click Add >>
Compress Objects Automatically: Yes
After changing all these things, remember that it can take some time for any old, cached values to expire from CloudFront. You can explicitly invalidate cached assets by going to the CloudFront distribution's Invalidations tab and creating an invalidation for *.
If you run Rails on Passenger and Heroku: (if not, jump straight to Noach Magedman's answer)
Noach Magedman's answer was very useful for me to set up CloudFront properly.
I also installed rack-cors exactly as described and whilst it worked fine in development, the CURL commands in production never returned any of the CORS configurations:
curl -H "Origin: https://tidyme-staging.com.au" -I http://tidyme-staging.com.au/assets/31907B_4_0-588bd4e720d4008295dcfb85ef36b233ee0817d7fe23c76a3a543ebba8e7c85a.ttf
HTTP/1.1 200 OK
Connection: keep-alive
Server: nginx/1.10.0
Date: Wed, 03 Aug 2016 00:29:37 GMT
Content-Type: application/x-font-ttf
Content-Length: 316664
Last-Modified: Fri, 22 Jul 2016 03:31:57 GMT
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
Cache-Control: public
Accept-Ranges: bytes
Via: 1.1 vegur
Note that I ping the server directly without going through the CDN, the CDN then after invalidating all content should just forward whatever the server responds. The important line here is Server: nginx/1.10.0, which indicates that assets are served by nginx and not Rails. As a consequence, the rack-cors configurations do not apply.
The solution that worked for us is here: http://monksealsoftware.com/ruby-on-rails-cors-heroku-passenger-5-0-28/
It basically involved cloning and modifying the nginx config file for Passenger, which is not ideal since this copy needs to be maintained every time Passenger gets upgraded and the template changes.
===
Here's a summary:
Navigate to the root folder of your Rails project and make a copy of the nginx config template
cp $(passenger-config about resourcesdir)/templates/standalone/config.erb config/passenger_config.erb
Open config/passenger_config.erb and comment this line out
<%# include_passenger_internal_template('rails_asset_pipeline.erb', 8, false) %>
Add these configurations below the line mentioned above
### BEGIN your own configuration options ###
# This is a good place to put your own config
# options. Note that your options must not
# conflict with the ones Passenger already sets.
# Learn more at:
# https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template
location ~ "^/assets/.+\.(woff|eot|svg|ttf|otf).*" {
error_page 490 = #static_asset_fonts;
error_page 491 = #dynamic_request;
recursive_error_pages on;
if (-f $request_filename) {
return 490;
}
if (!-f $request_filename) {
return 491;
}
}
# Rails asset pipeline support.
location ~ "^/assets/.+-([0-9a-f]{32}|[0-9a-f]{64})\..+" {
error_page 490 = #static_asset;
error_page 491 = #dynamic_request;
recursive_error_pages on;
if (-f $request_filename) {
return 490;
}
if (!-f $request_filename) {
return 491;
}
}
location #static_asset {
gzip_static on;
expires max;
add_header Cache-Control public;
add_header ETag "";
}
location #static_asset_fonts {
gzip_static on;
expires max;
add_header Cache-Control public;
add_header ETag "";
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, HEAD, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Max-Age' 3628800;
}
location #dynamic_request {
passenger_enabled on;
}
### END your own configuration options ###
Change the Procfile to include this custom config file
web: bundle exec passenger start -p $PORT --max-pool-size 2 --nginx-config-template ./config/passenger_config.erb
Then deploy...
===
If you know of a better solution, please put in the comments.
After implementing, the CURL command yielded the following response:
curl -H "Origin: https://tidyme-staging.com.au" -I http://tidyme-staging.com.au/assets/31907B_4_0-588bd4e720d4008295dcfb85ef36b233ee0817d7fe23c76a3a543ebba8e7c85a.ttf
HTTP/1.1 200 OK
Connection: keep-alive
Server: nginx/1.10.0
Date: Wed, 03 Aug 2016 01:43:48 GMT
Content-Type: application/x-font-ttf
Content-Length: 316664
Last-Modified: Fri, 22 Jul 2016 03:31:57 GMT
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
Cache-Control: public
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, HEAD, OPTIONS
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 3628800
Accept-Ranges: bytes
Via: 1.1 vegur
As of version 5.0, Rails allows for setting custom HTTP Headers for assets and you don't have to use the rack-cors or font-assets gems. In order to set Access-Control-Allow-Origin for assets (including fonts), just add the following code to config/environments/production.rb:
config.public_file_server.headers = {
'Access-Control-Allow-Origin' => '*'
}
The header value could also be a specific domain, like the following:
config.public_file_server.headers = {
'Access-Control-Allow-Origin' => 'https://www.example.org'
}
This worked for my app and I didn't need to change any settings on Cloudfront.
I just had the same issue and managed to solve it.
You've correctly told Cloudfront to allow those headers, but you haven't added those headers to where Cloudfront gets the font. Yes, your origin headers are allowed, but Heroku isn't sending those headers with the font anyway.
To fix this, you'll need to get the proper CORS headers added to the font on Heroku. Luckily, this is pretty easy.
First, add the rack/cors gem to your project. https://github.com/cyu/rack-cors
Next, configure your Rack server to load and configure CORS for any assets it serves. Add the following after your application preloads in config.ru
require 'rack/cors'
use Rack::Cors do
allow do
origins '*'
resource '/cors',
:headers => :any,
:methods => [:post],
:credentials => true,
:max_age => 0
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :patch, :options, :head],
:max_age => 0
end
end
This sets any resources returned from Heroku to have the proper CORS headers applied. You can restrict the application of headers depending on your file and security needs.
Once deployed, go into Cloudfront and begin an invalidation on anything that was previously giving you a CORS permission error. Now when Cloudfront loads a fresh copy from Heroku, it will have the correct headers, and Cloudfront will pass those headers on to the client as previously configured with your Origin permissions.
To make sure you're serving the proper headers from your server, you can use the following curl command to validate your headers:
curl -I -s -X GET -H "Origin: www.yoursite.com" http://www.yoursite.dev:5000/assets/fonts/myfont.svg
You should see the following headers returned:
Access-Control-Allow-Origin: www.yoursite.com
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS, HEAD
Access-Control-Max-Age: 0
Access-Control-Allow-Credentials: true
Here is a repo the demonstrates serving a custom font with Rails 5.2 that works on Heroku. It goes further and optimizes serving the fonts to be as fast as possible according to https://www.webpagetest.org/
https://github.com/nzoschke/edgecors
Asset Pipeline and SCSS
Place fonts in app/assets/fonts
Place the #font-face declaration in an scss file and use the font-url helper
From app/assets/stylesheets/welcome.scss:
#font-face {
font-family: 'Inconsolata';
src: font-url('Inconsolata-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
body {
font-family: "Inconsolata";
font-weight: bold;
}
Serve from CDN with CORS
I'm using CloudFront, added with the Heroku Edge addon.
If you're using your own CloudFront, make sure to configure it to forward the browser Origin header to your backend origin.
First configure a CDN prefix and default Cache-Control headers in production.rb:
Rails.application.configure do
# e.g. https://d1unsc88mkka3m.cloudfront.net
config.action_controller.asset_host = ENV["EDGE_URL"]
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=31536000'
}
end
If you try to access the font from the herokuapp.com URL to the CDN URL, you will get a CORS error in your browser:
Access to font at 'https://d1unsc88mkka3m.cloudfront.net/assets/Inconsolata-Regular.ttf' from origin 'https://edgecors.herokuapp.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource. edgecors.herokuapp.com/
GET https://d1unsc88mkka3m.cloudfront.net/assets/Inconsolata-Regular.ttf net::ERR_FAILED
So configure CORS to allow access to the font from Heroku to the CDN URL:
module EdgeCors
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
config.middleware.insert_after ActionDispatch::Static, Rack::Deflater
config.middleware.insert_before 0, Rack::Cors do
allow do
origins %w[
http://edgecors.herokuapp.com
https://edgecors.herokuapp.com
]
resource "*", headers: :any, methods: [:get, :post, :options]
end
end
end
end
Serve gzip Font Asset
The asset pipeline builds a .ttf.gz file but doesn't serve it. This monkey patch changes the asset pipeline gzip whitelist to a blacklist:
require 'action_dispatch/middleware/static'
ActionDispatch::FileHandler.class_eval do
private
def gzip_file_path(path)
return false if ['image/png', 'image/jpeg', 'image/gif'].include? content_type(path)
gzip_path = "#{path}.gz"
if File.exist?(File.join(#root, ::Rack::Utils.unescape_path(gzip_path)))
gzip_path
else
false
end
end
end
The ultimate result is a custom font file in app/assets/fonts served from a long-lived CloudFront cache.
Probably best is to use rack-cors gem. In the spirit of do-it-yourself and a follow-up to #GeekJock's answer. If one doesn't want to use rack-cors gem, this is poor man's CORS headers handling for a situation where for example we care only about static fonts assets (e.g. replacing the font_assets obsoleted gem).
Like in the other answer, you put in app config:
config.public_file_server.headers = {
'Access-Control-Allow-Origin' => '*'
}
To handle OPTIONS pre-flight requests, you can write a route matcher somewhere under /lib:
module FontAssetsConstraint
FONT_EXTENSIONS = %w[eot svg ttf otf woff woff2].freeze
module_function
def matches?(request)
extension = request.params["format"]
extension.present? && FONT_EXTENSIONS.include?(extension)
end
end
And then add a route definition config/routes.rb to catch those to reply:
Rails.application.routes.draw do
# Respond to pre-flight CSRF requests for font assets
if Rails.configuration.public_file_server.enabled &&
Rails.configuration.public_file_server.headers.include?("Access-Control-Allow-Origin")
constraints FontAssetsConstraint do
match "*path", via: :options, to: ->(hash) { [204, Rails.configuration.public_file_server.headers, []] }
end
end
Alternatively to writing a route matcher and a definition you can create your own middleware to catch fonts:
class AssetsOptionsResponder
TYPES = %w(eot svg ttf otf woff woff2).freeze
def initialize(app)
#app = app
end
def call(env)
if env["REQUEST_METHOD"] == "OPTIONS" && targeted?(env["PATH_INFO"])
[204, access_control_headers, []]
else
#app.call(env)
end
end
private
def targeted?(pathinfo)
return if pathinfo.blank?
TYPES.include? extension(pathinfo)
end
def extension(pathinfo)
pathinfo.split("?").first.split(".").last
end
def access_control_headers
Rails.configuration.public_file_server.headers
end
end
Then in app config or an initializer, you can add this middleware:
Rails.application.configure do
if defined?(ActionDispatch::Static) &&
Rails.configuration.public_file_server.enabled &&
Rails.configuration.public_file_server.headers.include?("Access-Control-Allow-Origin")
config.middleware.insert_before ActionDispatch::Static, AssetsOptionsResponder
end
end
# Gemfile
gem 'rack-cors'
# config/initializers/cors.rb
## very permissive
origins '*'
resource '*', headers: :any, methods: [:get]
## example of specifying only what's necessary
origins 'app.example.com'
resource '/packs/*', headers: :any, methods: [:get] # webpack
resource '/assets/*', headers: :any, methods: [:get] # asset pipeline
Working with Ruby 2.0 and Rails 4.0, I'm seeing a different behavior on my asset pipeline and I'm not sure why. Here's the gist of it...
I have in my ./app/assets/javascripts folder an application.js.coffee and google_analytics.js.coffee file.
In my app/views/layouts/application.html.haml, I have the following two lines:
= javascript_include_tag "application"
= javascript_include_tag "google_analytics"
This produces the following in the rendered page once deployed to production:
<script src="/assets/application-f15feb4200e0d1db4963a00b28fbe9ca.js"></script>
<script src="/javascripts/google_analytics.js"></script>
Note that the application include is compiled into the assets pipeline as expected, while the google_analytics script is not.
In development mode, everything's served from the assets pipe without the fingerprints as expected:
<script src="/assets/jquery.js?body=1"></script>
<!-- several other includes suppressed for brevity here -->
<script src="/assets/application.js?body=1"></script>
<script src="/assets/google_analytics.js?body=1"></script>
I also checked the production deployment and noted that google_analytics doesn't get pre-compiled and fingerprinted.
EDIT: After getting the comments and answers below, added the following to config/environments/production.rb and attempted another deploy:
ComingSoon::Application.configure do
config.serve_static_assets = false
config.assets.js_compressor = :uglifier
config.assets.compile = false
config.assets.digest = true
config.assets.version = '1.0'
config.assets.precompile += ['google_analytics.js.coffee']
end
Why is the sprockets assets pipeline not pre-compiling the google_analytics script and serving it up like it does the application script? how do I fix this?
You can add the google script to the precompile list in your config/environments/production.rb file on the config.assets.precompile setting. More here: What is the purpose of config.assets.precompile?
The google_analytics file needs to be added to the precompile list:
config.assets.precompile += ['google_analytics.js.coffee', ..]
Add above to your application.rb or production.rb as desired.
Note: Unless you have required the file in the application.js manifest file, through a direct require or through a require_tree, the js doesn't get compiled.
I have a Rails 4 application with
<%= javascript_include_tag "modernizr", "data-turbolinks-track" => true %>
in the head. In development, the following HTML is rendered, and modernizr is loaded:
<script data-turbolinks-track="true" src="/assets/modernizr.js?body=1"></script>
In production, the followign HTML is rendered, and modernizr is not loaded (404 not found):
<script data-turbolinks-track="true" src="/javascripts/modernizr.js"></script>
In production, /assets/modernizr.js is found and browsable.
The Rails documentation says that the javascript_include_tag should generate
<script data-turbolinks-track="true" src="/assets/modernizr.js?body=1"></script>
In production, my stylesheet_link_tags are fine, linking to the /assets/ directory.
Why is the javascript_include_tag linking to /javascripts instead of /assets in production, and how can I fix it?
One of the usage statements for AssetUrlHelper indicates it will produce /javascripts/ urls
like what you are seeing:
# asset_path "application", type: :javascript # => /javascripts/application.js
(from asset_url_helper.rb line 117 - [1])
This code looks like it can only be reached if the precompiled asset is missing
so it would appear that your asset compilation is not working (my deployments usually
fail when that happens, so maybe yours isn't even firing).
The same asset_url_helper.rb calls the /javascripts/ part 'extname' and
uses the following map to know how to generate the name:
# Maps asset types to public directory.
ASSET_PUBLIC_DIRECTORIES = {
audio: '/audios',
font: '/fonts',
image: '/images',
javascript: '/javascripts',
stylesheet: '/stylesheets',
video: '/videos'
}
A new Rails 4 app has this in the config/environments/production.rb
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
which seems to match the behavior you are seeing.
By default, Rails only precompiles application.js, application.css and any images it finds in the assets path. Therefore, in production mordernizr will not get precompiled and thus the javascript helpers will not be able to find the file.
In order to fix the issue, you can add modernizr to the precompile list by modifying the following config in production.rb
config.assets.precompile += ['modernizr.js']
For more information see the Rails Guides
Be sure to precompile your assets in production by running this command:
RAILS_ENV=production bundle exec rake assets:precompile
The Rails Guide on the asset pipeline can give you more details: http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets
I have a new application using Rails 4 deployed on Heroku with :
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
my javascript application.(fingerprint).js called from the src: assets/application.js
i think your problem come from something into your production.rb who define assets from another location.
So maybe you can add Moderniz.js to
config.assets.precompile = ['.js', '.css', '*.css.erb']
in config/production.rb
Or simply require modernizr script into your application.js
//= require mordernizr
and remove the modernizr script call into your layout.
<%= javascript_include_tag "modernizr", "data-turbolinks-track" => true %>
Can you check from where your application.js is served into your production environment ?
It may be because this file needs to be in /vendor/assets/javascript instead of /app/assets/javascript. The Vendor folder is for javascript libraries, and the App folder is for your code.
A better solution than adding a tag to your layout would be adding a script reference to your application.js and let the sass compiler compress and attach it to your main javascript file.
If you don't get a definitive answer, check out:
http://guides.rubyonrails.org/asset_pipeline.html#asset-organization