Link Custom CSS and Javascript to Rails After Deployment - css

I have a Rails App it's css and js links works fine locally since I have used :
<link href="assets/bootstrap.css" rel="stylesheet">
<link href="assets/bootstrap-responsive.css" rel="stylesheet">
<link href="assets/font-awesome.css" rel="stylesheet">
<link href="assets/bootswatch.css" rel="stylesheet">
I Googled more than it should all I find is this Heroku Guide , I'm so confused about the assets pipeline thing! I ran this command as well :
bundle exec rake assets:precompile
and it did create some files in the public dir as mentioned in the guide :
Now on Heroku Everything is plain, no design no nothing of Css and JS.
While when I run
Heroku Logs
This is what I get some serious NO Route Match for the CSS and JS files as follow :
2013-06-10T10:06:28.184255+00:00 app[web.1]: ActionController::RoutingError (No route matches [GET] "/assetscv.png"):
This is only one line, I get bunch of more of these for other files, and pre generated loggs lines
any help would be appreciated Thanks!
PS:
I tried
<%= stylesheet_link_tag "bootstrap" %>
<%= stylesheet_link_tag "bootstrap-responsiv" %>
<%= stylesheet_link_tag "bootswatch", "font-awesome.css" %>
I got bunch of errors and on heroku it says sorry something went wrong

In application.rb(config/application.rb)
# Enable the asset pipeline
config.assets.enabled = true
After this in production.rb file(config/environments/production.rb) do like this
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
#config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
then you should include all your js and css like this,
config.assets.precompile += %w(jquery.js jquery_ujs.js PIE.js check_list.js dom-drag.js jquery-1.4.2.min.js jquery-1.7.1.min.js jquery-1.8.3.js jquery-ui.js jquery.accordion.js jquery.corner.js jquery.countdown.js jquery.dimensions.js jquery.masonry.min.js jquery.tinycarousel.min.js jquery.validationEngine-en.js jquery.validationEngine.js questionnaire.js prototype.js users.js)
config.assets.precompile += %w(ie7.css ie8.css about_us.css admin_menu.css blog.css default.ultimate.css designer_directory.css designer_directorynew.css drop.css greenstore.css menu.css MenuMatic_dev.css message_view.css product.css setting1.css style1.css styles.css validationEngine.jquery.css)
After that precompile using this command
$ RAILS_ENV=production bundle exec rake assets:precompile
Then $ heroku restart
It should work.
For more details please read http://guides.rubyonrails.org/asset_pipeline.html

Related

Rails application not loading scss

I tried many things but my navbar is not showing properly on browser, just because sccs is not loading. This application was a Rails API Application and I converted to regular application. Maybe something went wrong on this process.
Assets/Stylesheets/application.scss
// Your CSS partials
#import "components/index";
Assets/Stylesheets/Components/_index.scss
// Import your components CSS files here.
#import "navbar";
Assets/Stylesheets/Components/_navbar.scss
Environments/development.rb
config.assets.debug = true
config.assets.quiet = true
config.assets.compile = true
application.rb
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module RailsJwt
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
I am new here so I don't know which other parts of my application I should show.
Since you converted an API-only Rails application to use CSS I'm assuming you haven't configured Webpacker to handle your front end assets. This link may be helpful: https://onrails.blog/2020/02/20/using-css-in-rails-6/
The most important for you is probably adding the following to your app/views/application.html.erb file:
<%= stylesheet_link_tag 'application', media: 'all' %>
If you're using Webpacker, adjust accordingly. Also, I don't think Rails 6 ships with the sprockets gem so you may have to add that to your Gemfile, unless you plan on using Webpacker.

stylesheet_pack_tag not finding app/javascript/src/application.css in rails 5.1 with webpacker gem

I am receiving this error when I try to load a page in my new rails 5.1 app using webpacker. I would like webpacker to handle CSS as well.
Started GET "/" for ::1 at 2017-09-01 12:20:23 -0400
Processing by HomeController#welcome as HTML
Rendering home/welcome.html.erb within layouts/application
Rendered home/welcome.html.erb within layouts/application (0.4ms)
Completed 500 Internal Server Error in 28ms
ActionView::Template::Error (Webpacker can't find application.css in /Users/myusername/Documents/testing-ground/myapp/public/packs/manifest.json. Possible causes:
1. You want to set wepbacker.yml value of compile to true for your environment
unless you are using the `webpack -w` or the webpack-dev-server.
2. Webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your Webpack configuration is not creating a manifest.
Your manifest contains:
{
"application.js": "/packs/application-1ba6db9cf5c0fb48c785.js",
"hello_react.js": "/packs/hello_react-812cbb4d606734bec7a9.js"
}
):
7: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
8: <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
9: <%= javascript_pack_tag 'application' %>
10: <%= stylesheet_pack_tag 'application' %>
11: </head>
12:
13: <body>
app/views/layouts/application.html.erb:10:in `_app_views_layouts_application_html_erb__1178607493020013329_70339213085820'
I am running the ./bin/webpack-dev-server alongside the rails server. I created the app using:
rails new myapp --webpack
bundle
bundle exec rails webpacker:install:react
I have a single CSS file app/javascript/src/application.css. (Writing that makes me feel something is wrong. Putting css inside of a javascript directory seems improper.)
I just have single root route defined root to: 'home#welcome'.
Here is app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Myapp</title>
<%= csrf_meta_tags %>
<%= javascript_pack_tag 'application' %>
<%= stylesheet_pack_tag 'application' %>
</head>
<body>
<%= yield %>
</body>
</html>
Here is my config/webpacker.yml (I have tried also setting compile to false in development.
# Note: You must restart bin/webpack-dev-server for changes to take effect
default: &default
source_path: app/javascript
source_entry_path: packs
public_output_path: packs
cache_path: tmp/cache/webpacker
# Additional paths webpack should lookup modules
# ['app/assets', 'engine/foo/app/assets']
resolved_paths: []
# Reload manifest.json on all requests so we reload latest compiled packs
cache_manifest: false
extensions:
- .coffee
- .erb
- .js
- .jsx
- .ts
- .vue
- .sass
- .scss
- .css
- .png
- .svg
- .gif
- .jpeg
- .jpg
development:
<<: *default
compile: true
dev_server:
host: localhost
port: 3035
hmr: false
https: false
test:
<<: *default
compile: true
# Compile test packs to a separate directory
public_output_path: packs-test
production:
<<: *default
# Production demands on precompilation of packs prior to booting for performance.
compile: false
# Cache manifest.json for performance
cache_manifest: true
I don't want to add too many details up-front incase they are more distracting then helpful. Please ask for anything else and I'll add to my question. Thanks!
In your application.js :
import "path to application.css"
I had this exact problem, on Rails 5.2 with Webpack's current version as of Dec 5, 2018 (4.2.x?) and just resolved it.
The fix for me was renaming application.css to anything else. I think there was a naming collision with Webpack.
So now my pack tags look like:
<%= stylesheet_pack_tag 'styles', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
I did NOT need to import the stylesheet inside application.js. This appears to make no difference for me.
OPTIONAL BONUS: I also renamed the app/javascript to app/webpack because I also thought it was confusing to run styles out of a Javascript directory (and learned from this youtube video that it could be done: https://www.youtube.com/watch?v=I_GGYIWbmg0&feature=youtu.be&t=32m35s). Simply:
Rename the directory to app/webpack
Adjust webpacker.yml like so: source_path: app/webpack
Hope that helps.
When HMR is set to false the styles are inlined within the bundle so you won't get any css bundle.
In your webpacker.yml file, setting hmr to true should fix your problem.
I realize this is an old question. Relevant, though.
In "config/environments/production.rb":
config.public_file_server.enabled = true
Delete "public/assets" and "public/pack"
And run:
RAILS_ENV=production bundle exec rake assets:precompile
I had the same problem and solved it with running yarn add postcss-smart-import in console.
upd: rails 5.2, webpacker 3.5, default config.
I had this problem or Rails 6.0.3.1.
I updated the file app/assets/config/manifest.js
//= link_directory ../../javascript/packs
//= link_directory ../images
Then restart in your terminal:
bin/webpack-dev-server
I had such problem even with import "path/to/application.css" line in application.js
In my case it was because test assets was precompiled with different node version
node modules was installed with node version v12
but test assets was compiled with with node version v10
assets were compiled but when I've looked inside public/pack-test/application.[hash].js and grep application.scss I saw an error line about node-sass missing.
In my cause problem was with Rubymine IDE - it somehow cache $PATH value from time when I had default node version v10 in nvm.
I hope my store will have somebody, who will encounter similar issue in future.
Revise Insallation Guide
Revise the version of webpacker (in package.json and Gemfile.lock with git story) if had recent changes withou you concerns.
All major errors are fixed when you revise: installation official guide
For me, for example, after revised I needed to add some files in /packs/application.js, include this at the top of the file:
import 'core-js/stable'
import 'regenerator-runtime/runtime'
I cleared webpacker's cache and it started working again for me:
rm -rf tmp/cache/webpacker

rails - application.css asset not found in production mode

I'm upgrading an application to use the asset pipeline.
I've got the css assets compiling into an application css file but they not being found when I run the application in production mode with
RAILS_ENV=production bundle exec rails s
and I visit any page I get the correct output from the database but no styling and the log shows:
ActionController::RoutingError (No route matches [GET]
"/assets/default.scss-1a27c...f07c.css"):
Even though that file exists in public/assets
$ ls public/assets/def*
public/assets/default.scss-1a27c...f07c.css public/assets/default.scss.css
public/assets/default.scss-1a27c...f07c.css.gz public/assets/default.scss.css.gz
What do I need to change to get the server to find the asset file?
Same is happening for my other .css files. They get compiled into public/assets with finger prints but then are not found.
Page source is showing:
<link href="/assets/default.scss-1a27c...f07c.css"
media="screen" rel="stylesheet" type="text/css" />
The rails (haml) source is = stylesheet_link_tag 'default.scss.css'
public.assets curently includes has the following files.
$ ls public/assets/def*
public/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css
public/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css.gz
public/assets/default.scss.css
public/assets/default.scss.css.gz
application.rb has
$ cat config/application.rb
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Linker
class Application < Rails::Application
config.encoding = "utf-8"
config.filter_parameters += [:password]
config.assets.enabled = true
config.assets.initialize_on_precompile = false # For Heroku
config.assets.version = '1.0'
end
end
config/environments/production has:
$ cat config/environments/production.rb
Linker::Application.configure do
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.assets.precompile += ['default.scss.css','main.css', 'jquery-ui-1.8.22.custom.css']
config.serve_static_assets = false
config.assets.compress = true
config.assets.compile = false
config.assets.digest = true
config.log_level = :debug
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
end
This seems to be happening for all assets, e.g.
Started GET "/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css"):
Started GET "/assets/main-6864687b4114a1c316e444bd90f233ff.css" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/main-6864687b4114a1c316e444bd90f233ff.css"):
Started GET "/assets/jquery-ui-1.8.22.custom-24319b4b1218846a3fe22a0479ae98b4.css" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/jquery-ui-1.8.22.custom-24319b4b1218846a3fe22a0479ae98b4.css"):
Started GET "/assets/application-fc1d492d730f2a45581a40eac4607db8.js" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/application-fc1d492d730f2a45581a40eac4607db8.js"):
Started GET "/images/link.ico" for 127.0.0.1 at 2014-02-23 10:24:48 -0500
ActionController::RoutingError (No route matches [GET] "/images/link.ico"):
Rails by default doesn't serve assets under public. See your production.rb:
config.serve_static_assets = true
Change that to true and you're good to go. (Note: you don't want that to be true in production, remember to change it back before deploying!)
See Configuring Rails Applications for details.
In rails 6, in the default production.rb there should be a line
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
So run your server with
RAILS_SERVE_STATIC_FILES=true rails server -e production
or set config.public_file_server.enabled=true in production.rb. See answers below for rails 4 and 5.
The Rails 5 solution is similar to the Rails 4 solution given by Jules Copeland above.
In your pre-generated config/environments/production.rb file, there should be an entry that looks something like this:
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
I found a decent explanation for this setting in the Configuring Rails Applications guide at http://guides.rubyonrails.org:
config.public_file_server.enabled configures Rails to serve static
files from the public directory. This option defaults to true, but in
the production environment it is set to false because the server
software (e.g. NGINX or Apache) used to run the application should
serve static files instead. If you are running or testing your app in
production mode using WEBrick (it is not recommended to use WEBrick in
production) set the option to true. Otherwise, you won't be able to
use page caching and request for files that exist under the public
directory.
Conclusion: In production, starting your rails server with RAILS_SERVE_STATIC_FILES=1 will allow Rails to serve any files in the public/assets directory just as a web server would. Keep in mind, Rails is an app server and will not do this as efficiently as a web server (e.g. NGINX, Apache, etc.). For real-world applications, you should have a dedicated web server sitting in front of Rails which will serve static assets by itself and only bother Rails for dynamic content as needed. For more details, see this article by Justin Weiss on the differences between web servers and app servers.
In Rails 4, you can get them to show in production (running locally), by passing an environment variable:
RAILS_SERVE_STATIC_FILES=true rails server -e production
This should work as long as you have this line in /config/environments/production.rb:
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
When you do rake assets:precompile, your assets go into public directory. See if you can find those files in public/assets/
You should see something like this:
I, [2014-02-23T20:06:21.853314 #26915] INFO -- : Writing app_root/public/assets/application-ecd8636fc80ea2b712039c4abc365da9.css

Wicked_pdf stylesheet not working on Heroku

I have a Rails app where I use wicked_pdf to generate PDF's. This is all fine and working locally, but when pushed to heroku the PDF does render, but without applying the stylesheet.
Especially for PDF rendering I have a CSS file: app/assets/stylesheets/pdf.css.scss. And in form.pdf.haml I load the stylesheet like this:
!!!
%html{lang: "en", "xml:lang" => "en", xmlns: "http://www.w3.org/1999/xhtml"}
%head
%meta{content: "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
= wicked_pdf_stylesheet_link_tag "pdf"
As said, it works great locally, but when pushed to heroku, I get this error:
ActionView::Template::Error (No such file or directory - /app/public/pdf.css)
What do I have to do to make this work on heroku?
Edit: I found this Gihub repo https://github.com/jordan-brough/heroku-pdf, which is an example app for using wicked_pdf on heroku. It really helped by adapting the environment.rb to serve a css file from the public folder when requesting a PDF.
I had a similar problem and it took me a while to crack. I ended up using the wkhtmltopdf-heroku gem and the following setup which works both locally and on heroku in addition to proper handling of the debug option:
In controller:
respond_to do |format|
format.html
format.pdf do
render pdf: #profile.name + Date.today.to_s(:number),
background: true,
encoding: 'utf8',
:show_as_html => params[:debug].present?
end
end
In show.pdf.erb:
<% if params[:debug].present? %>
<%= stylesheet_link_tag 'documents' %>
<% else %>
<%= wicked_pdf_stylesheet_link_tag 'documents' %>
<% end %>
... rest of view ...
In config/environments/production.rb:
config.assets.precompile += ['documents.css.scss.erb']
In config/initializers/assets.rb
Rails.application.config.assets.precompile += %w( documents.css )
Hope that this will be of help to someone.
I tried this solution and wicked_pdf works. But the comment:
"Activating runtime compilation is not the solution, because of the
performance hit we take" #David Tuite
and found answer in this comment with non-stupid-digest-assets gem, and works perfectly.
There is a GEM for the wkhtmltopdf binaries to work on heroku without you having to install any binaries in your own repository. It also comes packed with the OSX ( darwin ) binary for development. It worked with PDFKit and probably should work with WickedPDF as well
https://github.com/bradphelan/wkhtmltopdf-heroku
or in your Gemfile as
gem "wkhtmltopdf-heroku"

Django 1.3 rc1 and CSS

This is my configuration:
project_root
- (init, urls, settings, manage etc.).py
- templates
- - - <html files>
- - - <css files>
- - - <images>
- mainapp
my settings.py:
DEBUG = True
TEMPLATE_DEBUG = DEBUG
...
STATIC_ROOT = 'c:/static_collect/'
...
STATIC_URL = '/static/'
...
STATICFILES_DIRS = (
'c:/django-projects/myproject/mainapp/templates',
)
...
TEMPLATE_DIRS = ('c:/django-projects/myproject/mainapp/templates',)
my template references CSS files with {{ STATIC_URL}}style.css.
Everything works in development server. I view my CSS, static images and everything else.
Now I'm preparing to deploy a project, so I'm experimenting a little, before buying a hosting. Launched manage.py collectstatic and all of my static files in STATICFILES_DIRS were correctly copied to c:/static_collect.
I switched Debug = False to Debug = True. And my website doesn't load the stylesheet. I'm going crazy on this... templates are loaded but static files are simply not reachable.
Are not you allowed to put Debug=False in the development server?
Will it be solved once I put the project on a real production server?
Any ideas?
Thank you for your time.
The static files aren't added to the url patterns when debug is set to False. See staticfiles/urls.py:
if settings.DEBUG and not urlpatterns:
urlpatterns += staticfiles_urlpatterns()
You'll need to setup apache to serve the files, or add the urlpatterns yourself when debug is False (not recommended).

Resources