Keeping CSS out of JS in Angular 2/Angular-CLI - css

By default, Angular 2 compiles the CSS into JavaScript, especially when using WebPack as in Angular-CLI. I would rather this not happen for a couple of reasons.
The first reason is that when I'm developing, I find it really helps to be able to see in the developer tools exactly what style sheet a specific style rule was coming from and what line number it was on. The second reason is that I think compiling CSS into the code kind of misses the point of good CSS, which is that you can apply a different style sheet and have an entirely different look and feel with the same markup.
Is there a flag somewhere that I can set to leave the CSS in .css files, where IMO it belongs?

This is the whole point of encapsulated components.
A component should have it's own styles encapsulated with it so it can be shipped with the styles.
Imagine you want to publish one of your components to be used by others, shouldn't it have its own styles with it ?
That means Angular needs a way to link those css to the component , thus seperates them into chunks and injects them into head tag.
To solve your problem though , you have couple of options :
1- Not using the Emulated Encapsulation :
Components by default have a property called encapsulation which is set to Emulated , you need to change it to None:
#Component({
encapsulation:ViewEncapsulation.None
})
Then , you can put all you css in the head tag your self like you'd do with a normal html page.
2- If the problem is theme ing , you can make your component themeable .
You can have a theme attribute for your component and then based on that change the styleing :
#Component({
selector:'my-component',
styles:[
`
:host{
[theme="blue"]{
change what ever you want :
h1{
color:blue;
}
}
}
`
]
})
And then , using this component would be like :
<my-component [attr.theme]='"blue"'></my-component> // would be blue theme
<my-component></my-component> // would be default

Go to your base Html file(where the root module, main app is injected) and link the CSS stylesheets in your header section.
Webpack will not include it in it's compiled/combined css file which is injected into the page. The css file will still be included at run time in the browser.
<html>
<head>
<base href="/">
<meta charset="utf-8">
<title>dummy</title>
<meta name="viewport" content="width=device-width">
//was not injected/modified by webpack
<link rel="apple-touch-icon" sizes="57x57" href="app/images/apple-icon-57x57.png">
//webpack's injected this below from other components's imported/inline css rules
<link href="index-c2cacb5fa3dfbca6116f4e4e63d5c3c7.css" rel="stylesheet"></head>

With angular-cli 1.6.5 you can do this:
ng serve --extract-css
You will still have the style-encapsulation features, but devtools will now point to the component css source file.

I use the angular-cli as well (v1.0.0-beta.22). When I am ready to build for production I run the following command:
ng build -prod -aot
This generates all my production-ready files (bundled, tree-shaken and minified etc). Of particular note is that it will generate two versions of the style sheets.
One in js:
styles.b2328beb0372c051d06d.bundle.js
And another version is plain css:
styles.4cec2bc5d44c66b4929ab2bb9c4d8efa.bundle.css
I run some post-processing on the css file with gulp and use the css version for my production build. I am not sure if the same holds true for lazy loading (where the cli will produced different chunks), but it works for sure when lazy loading is not being used (I haven't launched a production-ready project yet with lazy loading).
I also tried a build with JiT compilation:
ng build -prod
It also produced the raw/minified version of the css style sheet.
Now, I know for sure the folowing does NOT work:
ng build
This will produce all the css embedded within js file, styles.bundle.js.
Since you want to use the raw css file during development, the only workaround I can think of is that you run ng build -prod in order to get the css file. Copy/paste this manually into your assets folder. Run "format" on the file to un-minify the file. Then do a normal build with a modified index.html file referencing your raw css file, and removing the styles.bundle.js script reference. Not pretty, but it might work.

Put a wrapper class in html example-
<div class="component-1-wrapper">
all yout html here inside component-1-wrapper
</div>
Structure your sass(scss) in the following way. Since your styles are wrapped inside component-1-wrapper, therefore it will apply only to component-1-wrapperclass
.component-1-wrapper{
// all the styles for component-1 here
.class-hello{
// styles
}
}
You can compile your css with sass and put all the css(seperated by modules) in seperate folder.Start the filenames by _, sass can import them:
You can refer your styles-main.scss in app.ts file
#component({
styleUrls:['styles/styles-main.scss']})
The style-sheets will be structured this way and individual component's class styles will be applied to particular component since there is a wrapper class in html
Hope it helps!!!!!!

Related

Vue 3 CSS files overlapping on component switch

I've imported some CSS files with
<style scoped>#import "../assets/XYZ.css";</style>
in different components. Now whenever I switch components the CSS from the other component is loading as well. Let's say I switch from Home.Vue to Blog.Vue, then Home.Vue's CSS file will be imported into Blog.Vue too. Whenever I refresh, everything seems to be fixed. Adding scoped doesn't seem to work for me.
I am using vue-router to switch between components.
This is my relevant code:
main.js
import './assets/main.css';
^ This is a css file to be used across my website on every component
Home.Vue
<style scoped>#import "../assets/home.css";</style>
Blog.Vue
<style scoped>#import "../assets/blog.css";</style>

AEM 6.5: Is there an HTL way to output Webpack-generated CSS within <style> tags from an AEM clientlib category?

Goal:
I have a specific clientlib ready with "critical CSS" that I would like to add to a page template in <style> tags, per Google's performance recommendations on a high-traffic e-Commerce site.
Problem:
We all know how to add a file reference in HTL:
<sly data-sly-use.clientlib="/libs/granite/sightly/templates/clientlib.html" data-sly-call="${clientlib.css # categories='template.noncritical'}"/>
but how would I output plain generated CSS styles on the page via HTL? Is there some other HTL property I could use?
I want this:
<style>
/* contents of AEM clientlib CSS here */
</style>
Tried:
I have Googled, searched StackOverflow, and looked in the AEM docs about clientlibs, but haven't found anything about inlining styles, except to
use a third-party script to inline critical CSS. (don't want to do)
modify HTML Library Manager OSGi configuration to inline all styles by default (don't want to do)
I am looking for something AEM-native that can be turned "on" or "off" in HTL. Thanks for reading and offering any solutions you may have.
You can try https://github.com/dmantsevich/aem-critical-css
It will generate CSS files and "integrate" with AEM. You can use it for extract small component CSS.
Some features:
CSS will be loaded only, if component presents on the page
Supports 2 injection types: <style /> and <link />
Supports less, css, scss.
CSS will be injected only once
Example:
MyComponentTemplate.html
<sly data-sly-use.aemCriticalCSS="${'./_aem-critical-css.js'}"
#aem-critical-css="my-component/my-component.scss">${aemCriticalCSS.inject # context="unsafe"}</sly>
Where my-component/my-component.scss is a path to css (related to ui.frontend/src/ folder). We used it on several projects and it helps to improve rendering performance. (path can be configured)
You can use the Core Components functionality https://experienceleague.adobe.com/docs/experience-manager-core-components/using/developing/including-clientlibs.html?lang=en#inlining
<style type="text/css"
data-sly-use.clientlibs="${'com.adobe.cq.wcm.core.components.models.ClientLibraries' # categories='wknd.base'}">
${clientlibs.cssInline # context="unsafe"}
</style>

How to reference a Sass stylesheet within SVG in a React App

For background, I am trying to load SVG icons in my react app and am using the object tag so that I can manipulate the color of the icons easily.
In this guide, they say:
If you want to use external styles, which are mostly much easier to work with and maintain, you can’t use or background-image. If you are using you need to reference your stylesheet internally from the SVG file (see code following). Remember: if you do this the SVG will also not be able to know what its parent class is (i.e. the ) so don’t try to use that in its styling. Inline SVGs don’t need this added and therefore can be slightly easier to work with in this sense.
and provide this code example:
// Add to very start of SVG file before <svg>
<?xml-stylesheet type="text/css" href="style.css"?>
// In style.css
.firstb { fill: yellow; }
.secondb { fill: red; }
To give you an idea of how my files are organized, my src folder contains an assets folder along with my components folder. My style.scss file lives within the src folder as well.
I'm having trouble figuring out what to add to the top of my svg files. My understanding of sass is that it would usually compile style.scss to style.css, however, when I look at my sources in dev tools it shows that style.scss is being loaded directly. Is this just because I'm still in development mode?
Anyways, I've tried the following (none of which have worked):
<?xml-stylesheet type="text/css" href="./style.scss"?>
<?xml-stylesheet type="text/css" href="style.css"?>
<?xml-stylesheet type="text/css" href="style.scss"?>
It would be a huge help if anyone knows how I can get this to work! Let me know if there's any other information I can provide. Thanks so much!
You are correct to assume that you'd need to compile style.scss to style.css, so first ensure that only the CSS is being referenced in the SVG. This is the most straightforward way to get this to work, but a better solution would be to import your styles once in your root HTML template instead.
Now, if you're using React it's likely that you're also using a bundler such as webpack. You can tell bundlers like webpack to handle non-JS imports such as Sass files by using loaders. There is a sass-loader for webpack that will allow you to import Sass files, however you may also need to add the svg-inline-loader so that you can import the SVG directly.
I think with both loaders, what will happen is that webpack will start bundling your React app, see that an SVG is imported, grab it and see that it is referencing a Sass file, grab the sass file and compile it, and then output the styles in your index.html file. Please let me know if this solution works for you!
I found a workaround. Not exactly what I was hoping for, but it works for me.
There's a react-svg package that handles an ajax request and pulls the svg in as a normal svg tag. This allows me to edit with my sass file.
https://www.npmjs.com/package/react-svg

Global styling vs local styling in VueJS

I'm building a project with .vue files which make it possible to write the CSS (SASS), JS and HTML in the same file.
I've decided to have some global components written in SASS on a assets/styles/app.scss file which will load my grid, variables and mixins.
On top of that, I want to be able to write some local SASS rules depending the component / page I'm on, seems pretty logical to want both in a project ...
Locally it looks like this:
<template>
</template>
<script>
</script>
<style lang="scss">
#import "assets/styles/app";
.my-style {
color: $my-variable;
}
</style>
It actually works, for instance I can use $my-variable in my local .vue file or any mixin I want. The problem is a VueJS project will grow and components will go together to display a page.
I noticed the global styling was loaded on each component, and the same rule is present in 5x, 10x when I open my chrome developer tool. This is still a very small project; all my styles are basically duplicated and loaded by the browser each time I add a component to the same page.
How do you avoid to load multiple times the global styles, while being able to use global SASS code in each components?
I've never worked with local mixed with global styling before, I preferred to just abstract totally the styling into a separated structure, but this is way more convenient to code with everything local in the same place.
What am I doing wrong here?
Detail: I'm on NuxtJS but I believe this issue is more related to VueJS overall.
Basically, every time you do an #import in your components it appends another copy to the main CSS file that Webpack generates.
Assuming you have the Webpack SCSS loader properly configured (which I believe you do since it compiles), you should be able to import the SCSS file once in your app.vue and the SCSS compiler will find it when it appends all other CSS.
For example, getting global fonts and mixins:
<style lang="scss">
#import url('https://fonts.googleapis.com/css?family=Lato:300,400,400i,700,900&subset=latin-ext');
#import "#/scss/mixins.scss";
</style>
Then create your CSS for each component inside the component's <style> section. Just make sure you add the lang="scss" so it all compiles.
You might also want to look into scss-resource-loader for Webpack. I think this is in the newest CLI builds, not sure about Nuxt.
in App.vue
<style lang="scss">
#import "assets/styles/common.scss";
</style>
OR
import compiled sass to css file in main.js
import './assets/styles/common.css';

Customizing Bootstrap CSS template

I am just getting started with Bootstrap from Twitter and am wondering what the ‘best practices’ is for customization. I want to develop a system that will take advantage of all the power of a css template (Bootstrap or other), be completely (and easily) modifiable, be sustainable (ie – when the next version of Bootstrap is released from Twitter I don’t have to start over.
For example, I want to add background images to the top navigation. It looks like there are 3 ways to go about this:
Modify the .topbar classes in bootstrap.css . I don’t particularly like this because I will have lots of .topbar items and I don’t necessarily want to modify them all the same way.
Create new classes with my background images and apply both styles (the new and the bootstrap to my element). This may create style conflicts, which could be avoided by stripping the .topbar class into separate classes and then only using the pieces that are not stepped on by my custom class. Again this requires more work than I think should be necessary and while it is flexible, it won’t allow me to easily update bootstrap.css when Twitter releases the next installment.
Use variables in .LESS to achieve the customization. Offhand this seems like a good approach but having not used .LESS I have concerns about compiling css on the client and about code sustainability.
Though I am using Bootstrap, this question can be generalized to any css template.
The best thing to do is.
1. fork twitter-bootstrap from github and clone locally.
they are changing really quickly the library/framework (they diverge internally. Some prefer library, i'd say that it's a framework, because change your layout from the time you load it on your page). Well... forking/cloning will let you fetch the new upcoming versions easily.
2. Do not modify the bootstrap.css file
It's gonna complicate your life when you need to upgrade bootstrap (and you will need to do it).
3. Create your own css file and overwrite whenever you want original bootstrap stuff
if they set a topbar with, let's say, color: black; but you wan it white, create a new very specific selector for this topbar and use this rule on the specific topbar. For a table for example, it would be <table class="zebra-striped mycustomclass">. If you declare your css file after bootstrap.css, this will overwrite whatever you want to.
Bootstrap 5 (update 2021)
As explained in the Bootstrap docs, modifying the existing "theme" colors is done using SASS. As with prior versions, you can also override the Bootstrap CSS by adding CSS rules that follow after the bootstrap.css and use the correct CSS specificity.
Bootstrap 5 - change theme colors
Bootstrap 4
I'm revisiting this Bootstrap customization question for 4.x, which now utilizes SASS instead of LESS. In general, there are 2 ways to customize Bootstrap...
1. Simple CSS Overrides
One way to customize is simply using CSS to override Bootstrap CSS. For maintainability, CSS customizations are put in a separate custom.css file, so that the bootstrap.css remains unmodified. The reference to the custom.css follows after the bootstrap.css for the overrides to work...
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
Just add whatever changes are needed in the custom CSS. For example...
/* remove rounding from cards, buttons and inputs */
.card, .btn, .form-control {
border-radius: 0;
}
Before (bootstrap.css)
After (with custom.css)
When making customizations, you should understand CSS Specificity. Overrides in the custom.css need to use selectors that are the same specificity as (or more specific) the bootstrap.css.
Note there is no need to use !important in the custom CSS, unless
you're overriding one of the Bootstrap Utility
classes. CSS
specificity
always works for one CSS class to override another.
2. Customize using SASS
If you're familiar with SASS (and you should be to use this method), you can customize Bootstrap with your own custom.scss. There is a section in the Bootstrap docs that explains this, however the docs don't explain how to utilize existing variables in your custom.scss. For example, let's change the body background-color to #eeeeee, and change/override the blue primary contextual color to Bootstrap's $purple variable...
/* custom.scss */
/* import the necessary Bootstrap files */
#import "bootstrap/functions";
#import "bootstrap/variables";
/* -------begin customization-------- */
/* simply assign the value */
$body-bg: #eeeeee;
/* use a variable to override primary */
$theme-colors: (
primary: $purple
);
/* -------end customization-------- */
/* finally, import Bootstrap to set the changes! */
#import "bootstrap";
This also works to create new custom classes. For example, here I add purple to the theme colors which creates all the CSS for btn-purple, text-purple, bg-purple, alert-purple, etc...
/* add a new purple custom color */
$theme-colors: (
purple: $purple
);
https://codeply.com/go/7XonykXFvP
With SASS you must #import bootstrap after the customizations to make them work! Once the SASS is compiled to CSS (this must be done using a SASS compiler node-sass, gulp-sass, npm webpack, etc..), the resulting CSS is the customized Bootstrap. If you're not familiar with SASS, you can customize Bootstrap using a tool like this theme builder I created.
Custom Bootstrap Demo (SASS)
Note: Unlike 3.x, Bootstrap 4.x doesn't offer an official customizer tool. You can however, download the grid only CSS or use another 4.x custom build tool to re-build the Bootstrap 4 CSS as desired.
Related:
How to extend/modify (customize) Bootstrap 4 with SASS
How to change the bootstrap primary color?
How to create new set of color styles in Bootstrap 4 with sass
How to Customize Bootstrap
I think the officially preferred way is now to use Less, and either dynamically override the bootstrap.css (using less.js), or recompile bootstrap.css (using Node or the Less compiler).
From the Bootstrap docs, here's how to override bootstrap.css styles dynamically:
Download the latest Less.js and include the path to it (and Bootstrap) in the <head>.
<link rel="stylesheet/less" href="/path/to/bootstrap.less">
<script src="/path/to/less.js"></script>
To recompile the .less files, just save them and reload your page. Less.js compiles them and stores them in local storage.
Or if you prefer to statically compile a new bootstrap.css with your custom styles (for production environments):
Install the LESS command line tool via Node and run the following command:
$ lessc ./less/bootstrap.less > bootstrap.css
Since Pabluez's answer back in December, there is now a better way to customize Bootstrap.
Use: Bootswatch to generate your bootstrap.css
Bootswatch builds the normal Twitter Bootstrap from the latest version (whatever you install in the bootstrap directory), but also imports your customizations. This makes it easy to use the the latest version of Bootstrap, while maintaining custom CSS, without having to change anything about your HTML. You can simply sway boostrap.css files.
You can use the bootstrap template from
http://www.initializr.com/
which includes all the bootstrap .less files. You can then change variables / update the less files as you want and it will automatically compile the css. When deploying compile the less file to css.
The best option in my opinion is to compile a custom LESS file including bootstrap.less, a custom variables.less file and your own rules :
Clone bootstrap in your root folder : git clone https://github.com/twbs/bootstrap.git
Rename it "bootstrap"
Create a package.json file : https://gist.github.com/jide/8440609
Create a Gruntfile.js : https://gist.github.com/jide/8440502
Create a "less" folder
Copy bootstrap/less/variables.less into the "less" folder
Change the font path : #icon-font-path: "../bootstrap/fonts/";
Create a custom style.less file in the "less" folder which imports bootstrap.less and your custom variables.less file : https://gist.github.com/jide/8440619
Run npm install
Run grunt watch
Now you can modify the variables any way you want, override bootstrap rules in your custom style.less file, and if some day you want to update bootstrap, you can replace the whole bootstrap folder !
EDIT: I created a Bootstrap boilerplate using this technique : https://github.com/jide/bootstrap-boilerplate
I recently wrote a post about how I've been doing it at Udacity for the last couple years. This method has meant we've been able to update Bootstrap whenever we wanted to without having merge conflicts, thrown out work, etc. etc.
The post goes more in depth with examples, but the basic idea is:
Keep a pristine copy of bootstrap and overwrite it externally.
Modify one file (bootstrap's variables.less) to include your own variables.
Make your site file #include bootstrap.less and then your overrides.
This does mean using LESS, and compiling it down to CSS before shipping it to the client (client-side LESS if finicky, and I generally avoid it) but it is EXTREMELY good for maintainability/upgradability, and getting LESS compilation is really really easy. The linked github code has an example using grunt, but there are many ways to achieve this -- even GUIs if that's your thing.
Using this solution, your example problem would look like:
Change the nav bar color with #navbar-inverse-bg in your variables.less (not bootstrap's)
Add your own nav bar styles to your bootstrap_overrides.less, overwriting anything you need to as you go.
Happiness.
When it comes time to upgrade your bootstrap, you just swap out the pristine bootstrap copy and everything will still work (if bootstrap makes breaking changes, you'll need to update your overrides, but you'd have to do that anyway)
Blog post with walk-through is here.
Code example on github is here.
Use LESS with Bootstrap...
Here are the Bootstrap docs for how to use LESS
(they have moved since previous answers)
you can start with this tool, https://themestr.app/theme , seeing how it overwrites the scss variables, you would get an idea what variable impacts what. its the simplest way I think.
example scss genearation:
#import url(https://fonts.googleapis.com/css?family=Montserrat:200,300,400,700);
$font-family-base:Montserrat;
#import url(https://fonts.googleapis.com/css?family=Open+Sans:200,300,400,700);
$headings-font-family:Open Sans;
$enable-grid-classes:false;
$primary:#222222;
$secondary:#666666;
$success:#333333;
$danger:#434343;
$info:#515151;
$warning:#5f5f5f;
$light:#eceeec;
$dark:#111111;
#import "bootstrap";

Resources