I have a rails engine that has a widget in it. I'm rendering the widget using a layout: false property in render and to style the widget, I'm recycling CSS on my main app.
Now here's the tricky part, I only needed 3 stylesheets for my widget and 2 of them are in my main app, those are bootstrap.css and _ss_font.css. On development, it works fine but when I push it to production, I'm having an error on bootstrap.css, it seems that it's dependent on another file on my vendor assets. How do I include those assets?
Note: If I use =stylesheet_link_tag "application" my problem is partially resolved but I have to handle conflicting class names and it will include all assets on my application. I just want to load the necessary stylesheets to style my widget in the engine.
EDIT 1
As suggested I'm including a more descriptive explanation on this:
So this is the error I'm having.
ActionView::Template::Error (File to import not found or unreadable:
ss-variables. Load path:
/data/serviceseeking_au_staging/releases/20140604114806 (in
/data/serviceseeking_au_staging/releases/20140604114806/vendor/assets/stylesheets/bootstrap.scss)):
2: !!! 5
3: %html
4: %head
5: = stylesheet_link_tag "bootstrap", "_ss_font", "feedback/reviews-widget"
6:
7: %body
8: .reviews-container
lib/action_logger.rb:31:in `call'
This view is inside the engine. As you can see, this is my ideal goal, to only include 3 stylesheets. There's not much to see on the reviews-widget, it's just sass without any external file dependency so I will not show it. So looking at the error message, where is this "ss-variable"? Well, let me take you guys on a field trip first before we arrive there.
I first traced where bootstrap.scss is and found it sitting on the main app under the vendor/assets/stylesheets folder. It's contents are as follows:
#import "bootstrap/variables";
#import "bootstrap/mixins";
#import "bootstrap/scaffolding";
#import "bootstrap/grid";
#import "bootstrap/layouts";
etcetera...
So by tracing boostrap.scss and opening it, I saw that it's importing a partial named _variables.scss, so on with the tour and here's _variable.scss
#import "ss-variables";
// Grays
// -------------------------
$black: #000 !default;
$grayDarker: #222 !default;
(Note: I saw another boostrap.scss inside the /vendor/assets/stylesheets/bootstrap where _variables.ss is located) Aha! There's that little freak, "ss-variable"!! We're getting close on this wild partial chase. So I searched where ss-variables.scss is and found it on my lib/assets/stylesheets/ in the main app and it contains more scss variables.
So tracing them, I formulated this hypothesis that when trying to include bootstrap using stylesheet_link_tag on my engine, the engine doesn't see the dependent files that lies on the main app.
Bonus: I have a remarkable feeling that after this, the _ss_font css will be next. But that's for another story. Thanks.
From the looks of it, your problem might be caused by the asset_fingerprinting feature of the asset pipeline - basically appends all the production assets with an MD5 hash
--
Asset Fingerprinting
Essentially, if you're using the likes of Heroku (which requires your assets to be precompiled for them to be served), you will basically get a series of files in your public/assets folder like this:
|-public
|--assets
|---images
|---stylesheets
|---javascripts
The files contained in this folder, when precompiled, all have the fingerprinted filename. This means if you wanted to call one of these, you will need to use one of the ERB / SCSS preprocessors to access them:
#app/assets/stylesheets/application.css.scss
.style {
background: asset_url("background.png");
}
This will reference the file, regardless of whether it's been precompiled (& fingerprinted) or not. Although not exactly your issue, it is an important factor in what you're asking
--
Fix
I would suggest your issue is likely that you're referencing "static" CSS files, which really need to be dynamically referenced.
How do I include those assets?
You'll be best using #import like this:
#gem/app/assets/gem/widget.css.scss
#import "bootstrap.css" /* will probably need a relative path for this */
#import "other.css" /* again, will need a relative path */
Related
When creating a new rails project with Rails 6, it creates an application.html.erb with stylesheet_link_tag to load CSS and javascript_pack_tag for javascript files.
Now, rails 6 also provide a stylesheet_pack_tag, so my question is, when to use it? And if we use it, do we need to add all CSS files in app/javascript folder?
What is the best practice to load css, images with rails 6 and webpacker?
You should use stylesheet_pack_tag if you are importing any CSS in Webpack AND if you have enabled extract_css: true for any environment in config/webpacker.yml.
Given the following directory structure:
app/
javascript/
packs/
application.js
styles/
site.css
And the following code in application.js:
import '../styles/site.css'
You would use <%= stylesheet_pack_tag 'application' %> in your view, i.e., the name of the stylesheet matches the name of the "pack".
At this point, I also recommend renaming app/javascript to something like app/frontend. So, the key changes in config/webpacker.yml:
source_path: app/frontend
extract_css: true
app/
frontend/
packs/
application.js
styles/
site.css
Just to try to clarify this a little. This is based on my current understanding, which seems to work well enough but still might not be fully accurate.
CSS processed by the asset pipeline gets a css_link_tag and css that is imported via a Webpacker javascript bundle is referenced with css_pack_tag.
Asset pipeline css is in app/assets/stylesheets. Webpack css is in app/javascripts/wherever_you_want.
So in webpack, all of the css imported into a javascript bundle is eventually extracted to a servable file that can be referenced via the same name as the js bundle.
So if in app/javascripts/application.js you have:
import 'app/javascripts/css/one.css'
import 'app/javascripts/css/two.css'
import 'app/javascripts/css/three.css'
These will be referenced with
css_pack_tag 'application'
This comes out looking like this in my deploy logs
Entrypoints:
application (430 KiB)
css/application-9d82d487.css
js/application-9f45d7ff735a7a203f28.js
It also bears noting, as was mentioned above that this behavior is affected by the extract_css setting.
Presumably this is false in development by default and true in production. One big GOTCHA with this is that, at least in my case, the css_pack_tag wasn't actually "required" in development, in the sense that removing it had no effect because it wasn't extracted locally. It still "worked" because the css was loaded in the javascript and seemed to be applied somehow that way. So I removed these tags thinking they were unnecessary before my understanding improved. Unfortunately when I deployed to production on heroku some time later, none of my css was working and it took me a while to figure out why and remember that I had removed these css_pack_tag lines.
I'm new to the whole JS/webpacker game and am failing to understand how to import and use a javascript package using webpacker.
I am trying to include and use the Animate On Scroll Library.
I have Webpacker installed and working (I know it's working because I am able to happily use StimulusJs).
Here's what my /javascript/packs/application.js file looks like:
import {
Application
} from "stimulus"
import {
definitionsFromContext
} from "stimulus/webpack-helpers"
import {
trix
} from "trix"
import AOS from "aos"
const application = Application.start()
const context = require.context("controllers", true, /.js$/)
application.load(definitionsFromContext(context))
AOS.init();
I have my javascript_pack_tag included on my application.html.erb as
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload', defer: true %>
I imported the required css files using my /assets/css/application.scss with #import 'aos/dist/aos'; so that shouldn't be the issue.
When I try and use the AOS package by doing something like <h1 class="text-center" data-aos="fade-in">This is a header.</h1> nothing happens. What am I missing?
Thanks.
Upon reading this again I guess it's more a JS issue you are encountering. I'll leave my points about the CSS below in case useful. See the fourth point about webpack-dev-server if you aren't using it already. Does your browser support defer? You could try moving the scripts to right before </body> to see. I'd probably just cut-to-the-chase and set a javascript breakpoint in AOS.init() and see what's happening.
A few points I've leaned recently to help better understand webpacker/css/sprockets...
First, the CSS in the assets folder is outside of webpack. It's sprockets. That's not a problem but often mixing the two presents challenges.
At the very least you'll need a stylesheet_link_tag 'application'... in addition to the pack tags.
Second, is AOS added via yarn or is it a gem? Gems with webpack can be a bit tricky. I and others I encountered gave up trying to use gem assets in webpack. Best to stick to yarn/npm modules for webpack. Otherwise, move all the assets into the sprockets pipeline (ie in the assets/ folder) and use that for this portion of your site. (it's ok to mix them, just keep them separate).
Third, if the AOS module is added via yarn add ... (ie it resides in the nodule_modules directory) then try replacing the CSS import to just
#import '~aos';
This works because node_modules is in the search path and if the plugin folder has a package.json manifest and it includes a "style" entry, it pulls the css file path from there.
Third, you can try moving the CSS to webpack. Try this...
Make an application.scss file in your components subfolder
Add to your packs/application.js file: import '../components/application.scss
Add a stylesheet_pack_tag 'application' .... to your layout
Put your css imports (from node modules) in your new application.scss
Fourth: Use bin/webpack-dev-server. This compiles webpack on the fly whenever any of your source files changes instead of on every page load (saves you a lot time). Since your CSS is now under webpack, it will give you errors if the import isn't right (though sprockets should do this too in your server logs).
Good luck! It gets easier and yarn/webpack is cool, better than the old ruby-gems-for-front-end-components, IMO
For a Rails application I am making I want to be able to switch 'themes' using a configuration file. The theme does not need to switch dynamically (while running, but will be known when the application starts).
I moved my stylesheets directory out of my assets directory, to a folder called : /app/themes/[themename]/assets/stylesheets.
The idea is to have multiple folders in the /app/themes directory, which can be used by the application.
REMARK: I didn't move my javascripts folder from the assets folder, because I still want to use that globally.
In my layout I use the following code, to load controller specific stylesheets:
<%= stylesheet_link_tag "#{controller_name}" if MyApp::Application.assets.find_asset("#{controller_name}") %>
Of course, my application no longer knows where my assets are and it serves me a page, where the assets are not loading (because of the if check mentioned above).
I added the following code to my config/initializers/assets.rb to make sure it also loads the assets from the theme directory:
Dir.glob("#{Rails.root}/app/themes/#{Settings.site.theme}/assets/**/").each do |path|
Rails.application.config.assets.paths << path
end
Settings.site.theme is a string value which is filled correctly and now the stylesheets actually load on the website. So YAY!
But here is the thing, the minute I change the config.assets.compile to false, it all fails (so on test and production).
MyApp::Application.assets.find_asset("#{controller_name}") is throwing the exception undefined methodfind_asset' for nil:NilClass`.
I am on Rails 5.0.0.1.
Anyone got an idea how to fix this?
I think a simpler way would be to namespace the themes under the stylesheets. That is, have a folder structure like this:
- app
- assets
- stylesheets
- theme-blue
- application.scss
- theme-red
- application.scss
- javascripts
- application.js
And then, in your layout file, you just point the stylesheet_link_tag to theme-blue/application, like this:
<%= stylesheet_link_tag "theme-blue/application" %>
Another way to do this is have multiple layouts, one for theme-blue and another one for theme-red. In the controller, do
class BlueController < ApplicationController
layout "theme_blue"
end
And the file app/views/layouts/theme_blue.html.erb will require the right css file.
You might need to add the scss files to config/assets.rb, but Rails will tell you if you need that.
Everyone knows how to use stylesheet_link_tag to link to a stylesheet, but I would like to actually include an entire stylesheet in a page itself. (No, this is normally not a great practice, but it makes sense in this context.)
stylesheet_include_tag does not exist, and a co-worker who is a much bigger bad-ass at Rails than I am says there isn’t a simple way.
Question:
Is it actually possible to make use of the asset pipeline and still embed the contents of a CSS or JavaScript file (compiled from Sass or CoffeeScript!) into a .haml view? How?
Added for clarity:
I’d like for my layout to be able to include something like:
= stylesheet_link_tag "base"
= stylesheet_embed_tag "page-specific-styles/foo"
And have this generate output HTML along these lines:
<link rel="stylesheet" href="/base.css" />
<style type="text/css">.foo { color: red; }</style>
Update
It’s possible to use Sass within Haml if you set your initalizer correctly, but I cannot seem to #import "foo" from this context, where foo.css.sass is a stylesheet in the asset pipeline. Note that #import "compass" (assuming you have the compass gem) does work.
This looks like (haml):
%style
:sass
#import "foo"
Rails gives an error that "foo" cannot be found, even though it claims to be looking in app/assets/stylesheets (which is where foo.css.sass lives).
So, this feels closer, but still not quite there.
from http://blog.phusion.nl/2011/08/14/rendering-rails-3-1-assets-to-string/ :
YourApp::Application.assets.find_asset('api.css').source
in haml
%style
=raw YourApp::Application.assets.find_asset('foo.css').source
caveats:
I believe this requires asset compilation in production, which can be pretty costly.
If I understand your question correctly, you could add your CSS code to a normal Ruby view file (as a partial), say styles.html.erb.
And then add that to your page upon any condition you want, I think it's the simplest way of looking at it.
Using Rails 3.2.1
I created a simple controller called Home using the command:
rails g controller Home index
And it created a new controller and view for me:
Notice how there are two stylesheets, one "Application" and one "Home". I can't find any documentation to support this assumption but I'm guessing you put styles that will only be applied to the "Home" views, in the Home.css.scss file, correct?
So as a test, I added in some global styles to Application.css.scss.erb and ran the application.
The styles applied as expected.
Next, I added in some rules to the Home.css.scss file and I visited a "Home/index" view, yet the style in that file wasn't attached, neither as a seperate CSS reference link, or even appended to the single Application.css.scss file. This is highly confusing to me, since the comments say:
// Place all the styles related to the Home controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
Why aren't the rules written in Home.css.scss applied to my website?
It can work this way and Marek is quite correct, the answer is in the guide.
In the introduction to section 2.1:
For example, if you generate a ProjectsController, Rails will also add a new file at app/assets/javascripts/projects.js.coffee and another at app/assets/stylesheets/projects.css.scss. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as <%= javascript_include_tag params[:controller] %> or <%= stylesheet_link_tag params[:controller] %>.
So to set your application up to load controller specific stylesheets:
First, disable the default loading of all stylesheets by removing any extra requires in the application.css manifest.
Typically you'll see an entry like this:
*= require_tree .
If you still want to load some common css files, you can move them to a subdirectory and do something like this:
*= require_tree ./common
Second, In your application's layout add the suggested stylesheet_link_tag eg
<%= stylesheet_link_tag "application", :media => "all" %>
<%= stylesheet_link_tag params[:controller] %>
In this example we first load the application css file, we then load any css file that matches the current controller name.
I've solved this problem with a simple solution. I add to body the controller name as a class, editing views/layouts/application.html.slim:
body class=controller.controller_name
Or views/layouts/application.html.erb:
<body class="<%= controller.controller_name%>">
And then in my css I just use body.controller_name as a namespace:
/* example for /users/ */
body.users {
color: #000;
}
body.users a {
text-decoration: none;
}
For small projects I think it's fine.
I don't think it works that way (Home.css being applied only to Home controller actions). The different files are just for separation, to make it clearer what are the CSS rules describing. You can read this guide about the asset pipeline. I'm guessing you altered the default application.css.scss and removed the line importing all CSS files from app/assets/stylesheets.
TL;DR:
Ignore the comment, it's not made by Sass. But put:
#import "*";
into your application.css.scss file, and it will automatically import all the controller scss files.
Full read:
Disclaimer: This is my current understanding of the asset pipeline flow with and without Sass.
I think this comment is written by the standard Rails Asset pipeline (sprockets), and not by Sass:
// Place all the styles related to the Home controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
The standard pipeline will handle scss files but doesn't presume an application.css.scss file. But if you create such a file with Sass, then Sass will compile it to the application.css file.
If you use the normal Rails asset pipeline, without Sass, then sprockets would load the css file into the application.css file automatically (if that file has the default *= require_tree . line in it).
When you use Sass, with an application.css.scss file, Sass will compile this file into a application.css file. (I assume it would overwrite or take precedence over any application.css file you already had).
To get your home.css.scss file (and other controller files) automatically included, put this line into your application.css.scss file:
#import "*";
For reference, see this question:
Is it possible to import a whole directory in sass using #import?