Stylus pre-processor won't work inside useref with gulpif - css

I have a very basic gulp task, and I want to process a Stylus CSS file (.styl). This is the task inside the gulpfile:
const gulp = require("gulp");
const gulpIf = require("gulp-if");
const useref = require("gulp-useref");
const stylus = require("gulp-stylus");
const cssnano = require("gulp-cssnano");
gulp.task("default", function(){
return gulp.src("*.htm")
.pipe(useref())
.pipe(gulpIf("*.css", stylus()))
.pipe(gulp.dest("dist"))
});
And this is the particular section of the html
<!--build:css css/style.min.css -->
<link rel="stylesheet" href="style.styl">
<!-- endbuild -->
For whatever reason, the Stylus file just doesn't get processed, and gets copied to css/style.min.css without any processing.
Even stranger, is that if I format the CSS as a normal CSS file and replace "stylus()" with "cssnano()", cssnano works fine and minifies the file. Stylus works fine outside of the useref and gulpIf when ran as its own task, but I preferably want to use it like this.

Can you try specifying the root path for useref where it can find assets:
options.searchPath
Type: String or Array Default: none
Specify the location to search for asset files, relative to the
current working directory. Can be a string or array of strings.
Your task
gulp.task("default", function(){
return gulp.src("*.htm")
.pipe(useref({
searchPath: 'assets_path_here'
}))
.pipe(gulpIf("*.css", stylus()))
.pipe(gulp.dest("dist"))
});
I personally just set the path to the root that contains my entire app.

Related

Gulpfile: How to compile each SCSS into separate CSS with same name but with additional common styles

First of all I'd like you guys to be gentle. I haven't been coding much in recent year and since gulp update when then changed syntax to writing functions and exporting I somehow made it work then and left with no changes up to this point, no clue if they changed something else. I've been happy with what it is right now, but I have no idea how to make it work the other way.
So anyway I'm working on a project right now, where there will be many htmls, and each one will have quite different styles, but some will be common. I want to make a main.scss file with common styles for each html, but I want to make a separate scss with styles specific to each html. This way in the end I want to have a separate css file made from a specific scss with same name combined with main.scss, so that it won't have to download a single large file, but only styles I need.
Example:
main.scss
01.scss
02.scss
03.scss
will compile to:
01.css ( main.scss + 01.scss )
02.css ( main.scss + 02.scss )
03.css ( main.scss + 03.scss )
This is my gulpfile right now:
const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync').create();
function style() {
return gulp.src('./scss/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'))
.pipe(browserSync.stream());
}
function watch() {
browserSync.init({
server: {
baseDir: './'
}
});
gulp.watch('./scss/**/*.scss', style);
gulp.watch('./*.html').on('change', browserSync.reload);
gulp.watch('./js/**/*.js').on('change', browserSync.reload);
}
exports.style = style;
exports.watch = watch;
If you have an idea how to do it in a better way I would really appreciate it.
I think you will have to import your main.scss into each of your other files and exclude main.scss from your gulp.src.
function style() {
return gulp.src(['./scss/**/*.scss', '!./scss/**/main.scss'])
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'))
.pipe(browserSync.stream());
}
'!./scss/**/main.scss' this negates or excludes that file from being passes into this task - I assumed main.scss was in the same folder as your other scss files, if that is not the case you will have to modify the path.
Then #import main.scss into each of your 01.scss, 02.scss, etc. files:
#import "main.scss"; // also assumes in same folder
You can put this import statement anywhere in the file, if it is first any of main.scss styles will be overridden by conflicting styles in the rest of the 0x.scss file. If you put the import statement at the end, then main.scss styles will override any previous conflicting styles.
Note: you should really be using #use instead of #import and gulp-dart-sass instead of gulp-sass at this point. See sass #use rule.
// in your gulpfile.js
const sass = require('gulp-dart-sass'); // once installed
#use "main.scss"; // must be at top of each scss file, such as 01.scss

Node.JS with Express and SASS - Compiled CSS file not applied

I'm new to NodeJS and I'm using Express to serve my pug files/view. Furthermore I'm using "express-sass-middleware" to compile and serve the scss/css files. Everything works very well but unfortunately, the CSS are not applied.
My app.js files looks like:
var express = require('express');
var sassMiddleware = require('express-sass-middleware');
var app = express();
app.set('view engine', 'pug');
app.get('/css/bootstrap.css', sassMiddleware({
file: 'css/bootstrap.scss', // the location of the entry point,
// this can also be a directory
precompile: true, // should it be compiled on server start
// or deferred to the first request
// - defaults to false
}));
app.get('/', function (req, res) {
res.render('index', {
varTitle: 'Hello World'
});
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
And my simple css file looks like:
// $icon-font-path: /3rdparty/fonts;
// #import 'bootstrap/bootstrap';
// #import './node_modules/bootstrap-sass/assets/stylesheets/bootstrap/variables';
body
{
background-color: green;
font-size: 100px;
}
My index.pug file is:
doctype html
html(lang='en')
head
title= varTitle
link(ref='stylesheet' type='text/css' href='/css/bootstrap.css')
body
h1= varTitle
Now, when I start my webserver using "node app.js", accessing http://localhost:3000, I see "Hello World" but unfortunately the body background isn't green and the text is also not 100px. That means that the css file is not applied. But when I access http://localhost:3000/css/bootstrap.css, I see the valid, css file.
Anyone know what I'm missing here? I'm a bit confused that I see the CSS source when accessing it directly but the browser doesn't apply the css styling. I already tried different browsers without any success. None of them applying the css file.
You have typing error in index.pug file for loading css file. You had mentioned ref whereas it should be rel.
link(rel='stylesheet' type='text/css' href='/css/bootstrap.css')
Happy to help you.
you don't seem to be serving the static files from your nodejs server code. You have to add your css dir in order to allow access from your html code:
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

Gulp CSS task not overwriting existing CSS

var paths = {
css: './public/apps/user/**/*.css'
}
var dest = {
css: './public/apps/user/css/'
}
// Minify and concat all css files
gulp.task('css', function(){
return gulp.src(paths.css)
.pipe(concatCSS('style.css'))
.pipe(minifyCSS({keepSpecialComments: 1}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest(dest.css))
});
When I first run the task it compiles alright and all changes are there.
After I change something and run it again it doesn't overwrite the existing minified css file. If I were to delete the minified css and run task again everything works perfect. Any insights?
Try and set the exact path, not a variable. Not that its not a good practice, just try without it.
Also , add a 'use strict'; to your task, so that you can be sure there are no serious errors with your settings. It will give you the right type of errors if there are any.
And, may I ask why are you concatenating your CSS before the production build?
Every file concatenation, minification and etc. should be performed in the 'build' task.
You have to delete your minified version of css before doing minify css.
To achieve this you can use gulp-clean
install gulp-clean as npm install gulp-clean
var gulp = require('gulp'),
concat = require('gulp-concat'),
cleanCSS = require('gulp-clean-css'), // this is to minify css
clean = require('gulp-clean'), //this is to delete files
gulp.task('del-custom-css', function(){
return gulp.src('./static/custom/css/custom.min.css',{force: true})
.pipe(clean())
});
gulp.task('minify-custom-css', ['del-custom-css'], function(){
return gulp.src(['./static/custom/css/*.css'])
.pipe(concat('custom.min.css'))
.pipe(cleanCSS())
.pipe(gulp.dest('./static/custom/css'))
});
Hope it helps.

Compile each SASS file with Gulp, creating multiple CSS files

I have the need to compile a SASS file to a CSS file when saved, without having to compile every SASS file to a single CSS file.
I need the ability to:
- Run a 'watch' on a directory
- If a file is saved, a CSS of it's name is created. Example: 'main.scss' compiles to 'main.css'.
- It should not compile every single SASS if it doesn't need to.
The goal is to optimize the development process to avoid compiling every single SASS file in a directory when 'watching'.
My current SASS task looks a bit like this and results in a single CSS file:
//Compile Sass
gulp.task('styles', function() {
return gulp.src('app/scss/styles.scss')
.pipe(plugins.sass({ includePaths : [paths.sass], style: 'compressed'})
.pipe(plugins.autoprefixer('last 2 version'))
.pipe(plugins.rename({suffix: '.min'}))
.pipe(plugins.minifyCss())
.pipe(gulp.dest('build/css'));
});
Looks like gulp-changed is what you're looking for:
https://github.com/sindresorhus/gulp-changed
You add it as a dependency with npm install --save-dev gulp-changed and plug it into your gulpfile. From the gulp-changed ReadMe:
var gulp = require('gulp');
var changed = require('gulp-changed');
var ngAnnotate = require('gulp-ng-annotate'); // just as an example
var SRC = 'src/*.js';
var DEST = 'dist';
gulp.task('default', function () {
return gulp.src(SRC)
.pipe(changed(DEST))
// ngAnnotate will only get the files that
// changed since the last time it was run
.pipe(ngAnnotate())
.pipe(gulp.dest(DEST));
});

How to use Sass inside a Polymer component

I'm currently using Polymer as my front end development framework. I love SASS.
Now I understand I can create a Sass file and import it like I normally would.
However, I've really gotten into the habit of using style tags within my web components.
Basically the workflow I am looking for is to be able to simply define a script tag within my Web Component maybe add type='sass; to it. Then have grunt go through and compile all of my SASS within those tags before outputting the files to my .tmp directory.
Is something like this achievable with something like Grunt or Gulp? If so what are the best modules to help me achieve this?
My implementation is based on a replacement of a tag inside the Polymer html file. I'm using gulp but could be changed to use simply fs.
The files structure should be as this example:
app-view
|- app-view.html
|- app-view.scss
app-view.html:
<dom-module id="app-view">
<template>
<style>
<!-- inject{scss} -->
</style>
</template>
</dom-module>
app-view.scss:
:host{
margin-top: 50px;
justify-content: center;
display: flex;
}
#container{
font-size: 12px;
h1{
font-size: 20px;
}
}
gulpfile.js:
var gulp = require('gulp');
var nodeSass = require('node-sass');
var path = require('path');
var fs = require('fs');
var map = require('map-stream');
var srcPath = 'src/';
var buildPath = 'build/';
var buildSrcPath = path.join(buildPath, 'target');
gulp.task('processComponents', function () {
return gulp.src([srcPath + '/components/**/*.html'])
.pipe(map(function (file, cb) {
var injectString = '<!-- inject{scss} -->';
// convert file buffer into a string
var contents = file.contents.toString();
if (contents.indexOf(injectString) >= 0) {
//Getting scss
var scssFile = file.path.replace(/\.html$/i, '.scss');
fs.readFile(scssFile, function (err, data) {
if (!err && data) {
nodeSass.render({
data: data.toString(),
includePaths: [path.join(srcPath, 'style/')],
outputStyle: 'compressed'
}, function (err, compiledScss) {
if (!err && compiledScss) {
file.contents = new Buffer(contents.replace(injectString, compiledScss.css.toString()), 'binary');
}
return cb(null, file);
});
}
return cb(null, file);
});
} else {
// continue
return cb(null, file);
}
}))
.pipe(gulp.dest(path.join(buildSrcPath, 'components')));
});
RESULT:
<dom-module id="app-view">
<template>
<style>
:host{margin-top:50px;justify-content:center;display:flex}#container{font-size:12px}#container h1{font-size:20px}
</style>
</template>
</dom-module>
First of all, a million Thanks and gratitude goes to David Vega for showing how it is done! I made some adaptations and optimized the code a little bit.
Here's the github for the file!
https://github.com/superjose/polymer-sass/tree/master
Well, this took me a while. Here it goes!
Polymer unleashed version 1.1. From its website:
Note: Style modules were introduced in Polymer 1.1; they replace the
experimental support for external stylesheets.
Instead, they now support "shared styles".
So this means that we can import .html files with css content. The problem is that we can't do .sass the normal way.
Fortunately here's a simpler solution.
What the following script does is that it gets your .scss files, parse them, and inject them into the shared style .html.
Here is the code. Below it, it's step by step on how to use and setup:
var gulp = require('gulp');
var nodeSass = require('node-sass');
var path = require('path');
var fs = require('fs');
var map = require('map-stream');
var basePath = "app/";
var excludeDir = basePath+"bower_components/";
var ext = "**/*.html";
/**
* We need to specify to nodeSass the include paths for Sass' #import
* command. These are all the paths that it will look for it.
*
* Failing to specify this, will NOT Compile your scss and inject it to
* your .html file.
*
*/
var includePaths = ['app/elements/**/'];
gulp.task('watchSass', function(){
gulp.watch(['app/**/*.scss', '!app/bower_components/**/*.scss'], ["injectSass"]);
});
//This is currently not used. But you can enable by uncommenting
// " //return gulp.src([basePath+ext,...excludeDirs])" above the return.
var excludeDirs = [`!${basePath}/bower_components/${ext}`,`!${basePath}/images/${ext}`]
/**
*
* Enable for advanced use:
*
*
*/
gulp.task('injectSass', function () {
/* Original creator: David Vega. I just modified
* it to take advantage of the Polymer 1.1's shared styles.
*
* This will look all the files that are inside:
* app/elements folder. You can change this to match
* your structure. Note, this gulp script uses convention
* over configuration. This means that if you have a file called
* my-element-styles.html you should have a file called
* my-element-styles.scss
*
* Note #2:
* We use "!" (Exclamation Mark) to exclude gulp from searching these paths.
* What I'm doing here, is that Polymer Starter Kit has inside its app folder
* all the bower dependencies (bower_components). If we don't specify it to
* exclude this path, this will look inside bower_components and will take a long time
* (around 7.4 seconds in my machine) to replace all the files.
*/
//Uncomment if you want to specify multiple exclude directories. Uses ES6 spread operator.
//return gulp.src([basePath+ext,...excludeDirs])
return gulp.src([basePath+ext, '!'+excludeDir+ext])
.pipe(map(function (file, cb) {
//This will match anything between the Start Style and End Style HTML comments.
var startStyle = "<!-- Start Style -->";
var endStyle = "<!-- End Style -->";
//Creates the regEx this ways so I can pass the variables.
var regEx = new RegExp(startStyle+"[\\s\\S]*"+endStyle, "g");
// Converts file buffer into a string
var contents = file.contents.toString();
//Checks if the RegEx exists in the file. If not,
//don't do anything and return.
//Rewrote the if for reduced nesting.
if (!regEx.test(contents)) {
//Return empty. if we return cb(null, file). It will add
//the file that we do not want to the pipeline!!
return cb();
}
/**
* Getting scss
* This will get the .html file that matches the current name
* This means that if you have my-app.component.html
* this will match my-app.component.scss. Replace with .sass if you
* have .sass files instead.
*/
var scssFile = file.path.replace(/\.html$/i, '.scss');
fs.readFile(scssFile, function (err, data) {
//Rewrote the if for reduced nesting.
//If error or there is no Sass, return null.
if (err || !data) {
return cb();
}
nodeSass.render({
data: data.toString(),
includePaths: [path.join('app', 'style/'), ...includePaths],
outputStyle: 'compressed'
}, function (err, compiledScss) {
//Rewrote the if for reduced nesting.
//If error or there is no Sass, return null.
if (err || !compiledScss)
return cb();
/**
* What we are doing here is simple:
* We are re-creating the start and end placeholders
* that we had and inject them back to the .html file
*
* This will allow us to re-inject any changes that we
* do to our .scss or files.
*
*/
var injectSassContent = startStyle +
"<style>" +
compiledScss.css.toString() +
"</style>" +
endStyle;
//This is going to replace everything that was between the <!-- Start Style --> and
// "<!-- End Style -->"
file.contents = new Buffer(contents.replace(regEx, injectSassContent), 'binary');
//This return is necessary, or the modified map will not be modified!
return cb(null,file);
});
});
}))
.pipe(gulp.dest(basePath));
}); //Ends
1) Setup your element:
Suppose you have an element called "hero-tournament":
<dom-module id="hero-tournament">
<template>
<style>
</style>
</template>
<script>
(function() {
'use strict';
Polymer({
is: 'hero-tournament',
});
})();
</script>
</dom-module>
And you want to inject your .scss file into it.
Create besides it two new files:
hero-tournament-style.html
hero-tournament-style.scss
Inside the first file, hero-tournament-style.html write the following:
<!-- hero-tournament-style.html -->
<dom-module id="hero-tournament-style">
<template>
<!-- Start Style -->
<style>
</style>
<!-- End Style -->
</template>
</dom-module>
Note the:
<!-- Start Style --> <!-- End Style -->
comments?
These are SUPER important, as all the css will go inside these ones. These are case sensitive, but not position sensitive. Be sure to include them inside your template tags and outside of your style tags.
Then on your hero-tournament-style.scss file, include your sass' css:
(Example)
.blank{
display: none;
}
2) Run Gulp:
gulp watchSass
Bam! You'll see that your "hero-tournament-style.scss" file will be overwritten with your css!!!
<!-- -hero-tournament-style.html -->
<dom-module id="-hero-tournament-style">
<template>
<!-- Start Style -->
<style>.blank{display:none}
</style><!-- End Style -->
</template>
</dom-module>
Now, you can refer that file anywhere!!! Remember your first element, the original one ("hero-tournament.html")? Do the following to it:
<!-- import the module -->
<link rel="import" href="../path-to-my-element/.html">
<dom-module id="hero-tournament">
<template>
<!-- include the style module by name -->
<style include="hero-tournament-styles"></style>
</template>
<script>
(function() {
'use strict';
Polymer({
is: 'hero-tournament',
});
})();
</script>
</dom-module>
Some last notes:
Using SASS Imports
Using Sass imports is easy, just need to watch out for the following:
In the gulpfile there is a variable called: "includePaths". It's an array in which nodeSass will look for all the imports. Failing to specify your import in any of the mentioned places, will prevent your file from injecting and compiling. By default, in the script there is a 'app/style' directory which will look for it.
Folder structure
Folder structure is important, and it can be adapted as your liking.
This assumes that your elements are inside an "app" folder brother to your gulpfile (In the same hierarchy):
-gulpfile.js
/app
/element
/hero-tournament
-hero-tournament.html
-hero-tournament-styles.html
-hero-tournament-styles.scss
/maybe-other-folder
If you want to change your folder structure, change the "basePath" variable. Be sure to check for leading "/" so you don't mess up your structure!
How do I run my gulpfile?
It's easy:
Call the "watchSass" method for watching, or "injectSass" for using it once.
gulp watchSass
gulp injectSass
More information in the github page!!!
In Polymer 2.0 it's also possible to just import a stylesheet inside the element's template like that:
<dom-module id="your-module-name">
<template>
<style><!-- you can also add additional styling in here --></style>
<link rel="stylesheet" href="link_to_stylesheet.css">
<!-- your template in here -->
</template>
<script>
//your element class + registration here
</script>
</dom-module>
Inside of the stylesheet you can style your content just like in the style-tag. The styles only affect the element and its content.
If you want to use SASS, Stylus, LESS or anything like that, you just have to use a middleware (HOWTO: Stack Overflow) in Express that renders the SASS-Code into CSS on every request. I prefer this solution over GULP/GRUNT task, because I think it's way easier, because you don't always have to run the Task, because of the Middleware it's compiling automatically whenever it's needed.
I hope that helps you

Resources