How to switch css file when using Webpack to load css? - css

I use gulp to compile my sass file to css files, and reference the css file in my html. The project support theme switch. For example, I have 3 css theme files:
red.css
yellow.css
blue.css
I can currently switch the theme css like this:
var styleDom = $('#theme-style');
var newHref = 'styles/themes/' + themeName + '.css';
if (styleDom.attr('href') !== newHref) {
styleDom.attr('href', newHref);
}
Now I want to use webpack to load the css file.
require('styles/themes/red.css');
It seems work well, but I cannot find a way to switch the theme css file now, does anyone have a solution?

Your approach doesn’t need to change. Just use Extract Text plugin to save out the CSS files. You’ll need to make multiple entry points to create multiple CSS files.
OR
More ideally, (the approach I would take) make your CSS switch based on a different html or body class and just change the class. It won’t add much overhead, and it will be a more ideal UX when changing themes.

You'll need to use a combination of webpacks style-loader and file-loader (second example ) and use require.ensure (second example "dynamic imports") to accomplish this:
function switchTheme(name) {
// Remove the current theme stylesheet
// Note: it is important that your theme css always is the last
// <link/> tag within the <head/>
$('head link[rel="stylesheet"]').last().remove();
// Since webpack needs all filePaths at build-time
// you can't dynamically build the filePath
switch(name) {
case 'red':
// With require.ensure, it is possible to tell webpack
// to only load the module (css) when require is actually called
return require.ensure([], function () {
require('style-loader/url!file-loader!styles/themes/red.css');
});
case 'yellow':
return require.ensure([], function () {
require('style-loader/url!file-loader!styles/themes/yellow.css');
});
case 'blue':
return require.ensure([], function () {
require('style-loader/url!file-loader!styles/themes/blue.css');
});
default:
throw new Error('Unknown theme "' + name + '"');
}
}
Then a call like switchTheme('blue') should do the trick.
And you might have to check your current webpack.config.js, in case you already have configured a loader for .css files.

Related

How to prefix Bootstrap 4 classes to avoid css classes conflict

I am working on building small applications that will live in a website. The website that will host these applications may or may not be using a css framework. I Want to prefix all Bootstrap classes with my own unique prefix.
To avoid "ANY INSTANCE or CHANCE" of conflict I want to prefix all Bootstrap CSS classes with - let's say - "year19-" prefix. So, for example, all the col- classes would now be year19-col- and all the .btn classes would now become .year19-btn, .year19-btn-primary, etc...
I know if I use the sass theme, new classes, then we would get around some of that as we can create our own prefixes using the theming approach, but JS would still remain a source of conflict if two versions of the same framework live on the same page. There was a Github project for Bootstrap 3 with the namespacing feature where you could just add your prefix in the namespace variable then compile the entire code to a CSS and JS package. Bootstrap 4 doesn't seem to have that package yet.
Also, I don't want to wrap the project with a css class. That approach is fine for some things, but not the right approach. I wouldn't even call that namespace. That is just wrapping the classes.
year19-btn-primary {
then this would be whatever the code that already existed there before, not touched.}
I managed to get classes prefixed for Bootstrap 5.1.3. You'll need to make the following changes before compiling Bootstrap yourself. My full implementation is available here: https://github.com/Robpol86/sphinx-carousel/tree/85422a6d955024f5a39049c7c3a0271e1ee43ae4/bootstrap
package.json
"dependencies": {
"bootstrap": "5.1.3",
"postcss-prefix-selector": "1.15.0"
},
Here you'll want to add postcss-prefix-selector to make use of it in postcss.
postcss.config.js
'use strict'
const prefixer = require('postcss-prefix-selector')
const autoprefixer = require('autoprefixer')
const rtlcss = require('rtlcss')
module.exports = ctx => {
return {
map: ctx.file.dirname.includes('examples') ?
false :
{
inline: false,
annotation: true,
sourcesContent: true
},
plugins: [
prefixer({
prefix: 'scbs-', // ***REPLACE scbs- WITH YOUR PREFIX***
transform: function (prefix, selector) {
let newSelector = ''
for (let part of selector.split(/(?=[.])/g)) {
if (part.startsWith('.')) part = '.' + prefix + part.substring(1)
newSelector += part
}
return newSelector
},
}),
autoprefixer({
cascade: false
}),
ctx.env === 'RTL' ? rtlcss() : false,
]
}
}
This is where the CSS will be prefixed. I'm using postcss instead of just wrapping bootstrap.scss with a class/id selector so I can use the Bootstrap 5 carousel component on Bootstrap 4 webpages (which is my use case). This will replace https://github.com/twbs/bootstrap/blob/v5.1.3/build/postcss.config.js
rollup.config.js
// ...
const plugins = [
replace({ // ***COPY/PASTE FOR OTHER BOOTSTRAP COMPONENTS***
include: ['js/src/carousel.js'], // ***YOU MAY NEED TO REPLACE THIS PATH***
preventAssignment: true,
values: {
'CLASS_NAME_CAROUSEL': '"scbs-carousel"', // ***USE YOUR PREFIXES HERE***
'CLASS_NAME_ACTIVE': '"scbs-active"',
'CLASS_NAME_SLIDE': '"scbs-slide"',
'CLASS_NAME_END': '"scbs-carousel-item-end"',
'CLASS_NAME_START': '"scbs-carousel-item-start"',
'CLASS_NAME_NEXT': '"scbs-carousel-item-next"',
'CLASS_NAME_PREV': '"scbs-carousel-item-prev"',
'CLASS_NAME_POINTER_EVENT': '"scbs-pointer-event"',
'SELECTOR_ACTIVE': '".scbs-active"',
'SELECTOR_ACTIVE_ITEM': '".scbs-active.scbs-carousel-item"',
'SELECTOR_ITEM': '".scbs-carousel-item"',
'SELECTOR_ITEM_IMG': '".scbs-carousel-item img"',
'SELECTOR_NEXT_PREV': '".scbs-carousel-item-next, .scbs-carousel-item-prev"',
'SELECTOR_INDICATORS': '".scbs-carousel-indicators"',
}
}),
babel({
// Only transpile our source code
// ...
Lastly rollup replace plugin is used to add the prefixes in the compiled javascript file. I wasn't able to find a way to just prefix the consts so I had to resort to having the entire const replaced and hard-coded with the full class names. This means you'll need to do this for every Bootstrap component that you're including in your final build (for me I just need the carousel so it's not a big deal).

Choose between different style for an Ember.JS application

The issue I have is that I can't find a way to 'change' the css style within my application.
The thing that I want to access is for example: I have a red theme, but I want that the user can choose an other predefined theme, like a green, or a blue theme.
The idea is that I have different app.css, how can I change between one another, I can't find method to do so. Maybe I can do it in my environnement.js?
Any tips is apreciated.
tl;dr: How to set multiple css style in our Ember.JS app?
You can achieve this by generating multiple stylesheets, see: https://ember-cli.com/asset-compilation#configuring-output-paths
I suggest using ember-cli-head to add a specific link element with the additional theme stylesheet. You could set the stylesheet in your head.hbs using the headData service.
Full Example:
ember-cli-build.js
var app = new EmberApp({
outputPaths: {
app: {
css: {
// app/styles/red.css
'red': '/assets/themes/red.css'
}
}
},
// Exclude theme css files from fingerprinting,
// otherwise your file is named `red-somehash.css`
// which we don't (easily) now at runtime.
fingerprint: {
exclude: [ 'red.css' ]
}
})
head.hbs
{{#if theme}}
<link rel="stylesheet" href="/assets/{{theme}}.css">
{{/if}}
some-component.js (or Route or whatever)
export default Ember.Component.extend({
headData: Ember.inject.service(),
actions: {
setTheme(themeName) {
this.set('headData.theme')
}
}
})

How to set proper base for the input files for gulp-concat-css?

I am using gulp-concat-css to combine a selected list of CSS into one. My project folder structure look like this:
[]Project Folder
gulpfile.js
---[]public
------[]assets
---------[]libs (All bower install libraries such as bootstrap will be placed here)
---------[]css (All my custom CSS including the combined CSS will be placed here)
Now, my gulp task look something like this:
gulp.task('concatcss', function() {
return gulp.src(['public/assets/libs/bootstrap/dist/css/bootstrap.min.css',
'public/assets/libs/angular-motion/dist/angular-motion.min.css',
'public/assets/libs/bootstrap-additions/dist/bootstrap-additions.min.css',
'public/assets/libs/blueimp-file-upload/css/jquery.fileupload.css',
'public/assets/css/mycustom.css'])
.pipe(concatCss("css/all.css").on('error', standardHandler))
.pipe(minifyCss().on('error', standardHandler))
.pipe(gulp.dest('public/assets'));
});
The problem is the final output come with the wrong url rebase. This cause the CSS URL is pointing to the wrong path of files. For example, the original URL from the bootstrap.min.css is url('../fonts/glyphicons-halflings-regular.woff'). Now, the combined CSS come with the URL of url(../../fonts/glyphicons-halflings-regular.woff), which is wrong. It should be url(../libs/bootstrap/dist/fonts/glyphicons-halflings-regular.woff)
According to gulp-concat-css documentation, it says "for a proper import inlining and url rebase, make sure you set the proper base for the input files".
How can I set the proper base for the input files to get the correct url rebase?
You have to set the base as option in gulp.src like this { base: 'public/assets' }:
gulp.task('concatcss', function() {
return gulp.src(['public/assets/libs/bootstrap/dist/css/bootstrap.min.css',
'public/assets/libs/angular-motion/dist/angular-motion.min.css',
'public/assets/libs/bootstrap-additions/dist/bootstrap-additions.min.css',
'public/assets/libs/blueimp-file-upload/css/jquery.fileupload.css',
'public/assets/css/mycustom.css'], { base: 'public/assets' })
.pipe(concatCss("css/all.css").on('error', standardHandler))
.pipe(minifyCss().on('error', standardHandler))
.pipe(gulp.dest('public/assets'));
});

Inlining data-urls with Stylus and Gulp

Currently I have a stylus file that imports another stylus file. This second file uses the URL function like this, and I want it to be inlined (e.g. to a base 64 data-url). However this isn't working when run through my gulp pipeline
lines.styl:
vertical-img = 'vertical.svg';
#import "../tree";
tree.styl
background-image: url(vertical-img)
What I want to get as a result is:
background-image: url('data:image/svg+xml;utf8,<svg>[...]</svg>');
But I get this:
background-image: url("vertical.svg")
And my gulpfile is as follows:
return gulp.src('src/css/*/*.styl')
.pipe(gstylus({
set: ['resolve url']
}))
.pipe(rename(function (file) {
file.dirname = "";
file.extname = ".css";
}))
.pipe(gulp.dest(DEST))
Basically it seems like the 'resolve url' option isn't being passed to stylus. I'm aware that I need it, since it says in the Stylus Docs that:
By default Stylus doesn’t resolve the urls in imported .styl files, so if you’d happen to have a foo.styl with #import "bar/bar.styl" which would have url("baz.png"), it would be url("baz.png") too in a resulting CSS.
But you can alter this behavior by using --resolve-url (or just -r) CLI option to get url("bar/baz.png") in your resulting CSS.
The correct option for image inlining is url (not resolve url) see http://learnboost.github.io/stylus/docs/functions.url.html. To use it in gulp-stylus you should pass url option to options object (see https://github.com/jenius/accord/blob/master/docs/stylus.md#url). For example:
return gulp.src('src/css/*/*.styl')
.pipe(gstylus({
url: { name: 'url', limit: false }
}))
.pipe(rename(function (file) {
file.dirname = "";
file.extname = ".css";
}))
.pipe(gulp.dest(DEST))

Dynamic scss variable meteor

I have a scss variable $tint-color that is used in about 100 places.
Once the user logs in, I would like to load a color based on their profile and replace all the usages of $tint-color.
So far I have found two non-ideal solutions:
1) Iterate through all elements and replace the relevant properties.
I am constantly generating new elements -- so this would need to happen repeatedly.
2) Create an override stylesheet, that targets each element.
This will require a lot of duplicate code.
Is there a better / simpler way? I have thought about adding a class to an element in scss, but I am not sure this is possible. Thank you for your help in advance!
What I am doing now, is loading a theme css file after the profile is loaded.
On the server I expose an iron-router route that dynamically replaces any occurrence of the color and returns the theme css.
The issue is that I am not replacing the scss variables, instead I am replacing any occurrence of the color. This is because when the code is executed the .scss files have already been bundled into a .css file on the server.
// return a theme based on the tintColor parameter
this.route('theme', {
where: 'server',
action: function () {
var files = fs.readdirSync('../client');
// find the css file (not the .map file)
var cssFile = _(files).find(function (fileName) {
return fileName.indexOf('.css') > 0 && fileName.indexOf('.map') < 0;
});
var style = fs.readFileSync('../client/' + cssFile, 'utf8');
// remove comments (cannot have them for minification)
style = style.replace(/(?:\/\*(?:[\s\S]*?)\*\/)|(?:([\s;])+\/\/(?:.*)$)/gm, '');
// replace the default tint-color with the dynamic color
style = style.replace(/8cb850/g, this.params.tintColor);
// minify css
if (Settings.isProduction()) {
// from the minifiers package
style = CssTools.minifyCss(style);
}
this.response.writeHead(200, {'Content-Type': 'text/css'});
this.response.end(style);
}
});
Update: I got it to generate with scss variables.
Theme.compile = function (tintColor) {
var dirName = path.dirname(styleFile);
var styles = fs.readFileSync(styleFile, 'utf8');
//replace default theme with dynamic theme
var theme = '$tint-color: #' + tintColor + ';' + '\n';
styles = styles.replace('#import "app/theme.scssimport";', theme);
var options = {
data: styles,
sourceComments: 'map',
includePaths: [dirName] // for #import
};
var css = sass.renderSync(options);
// minify css
if (Settings.isProduction()) {
// remove comments -- cannot have them for minification
css = css.replace(/(?:\/\*(?:[\s\S]*?)\*\/)|(?:([\s;])+\/\/(?:.*)$)/gm, '');
// Use CssTools from the minifiers package
css = CssTools.minifyCss(css);
}
return css;
};
If you do this make sure you add the scss files as assets in the package, example here.
Set a basic $tint-color in your original css.
Then use meteor to send inline CSS with the selected user-tint.
Example:
.tint {
background-color: USER-TINT;
color: USER-TINT;
}
That way you can cache the original css file and save loads of transfer!

Resources