I'm looking for a plugin chain to use with Gulp that provides:
source map support
less
minification
concatenation
URL replacement (rebase) to address relocation/concat
I currently have the first four, but I can't find a combination of existing plugins that will give me the last (URL rebasing) also. I've not found any URL rebasing plugins that emit sourcemaps.
Just to be clear, my issue is that when I compile multiple small CSS files from my project development folders, and output them into a common folder, the move resulting from concatenation breaks relative URLs, such as those for background images.
EDITS:
It sounds like the tool chain I currently use is already intended to solve this problem. So, that's ostensibly the answer. However, that raises another question, how the required syntax is supposed to work.
That question theoretically has lots of duplicates out there:
clean-css #152: Rebasing functionality very frustrating
clean-css #195: root option on Windows
clean-css #263: How to get relativeTo option working with CSS files in different paths
http://adilapapaya.com/docs/clean-css/#howtorebaserelativeimageurls
Grunt cssmin rebasing a relative URI?
Unfortunately no answers actually explain the syntax, they just demonstrate voodoo; so I don't know why the following isn't working. If I can get it resolved I'll come back here and flag this accepted to indicate this tool chain does actually do what I need.
The source files:
/assets
/site
styleInput1.less "url(../site/logo.png)"
logo.png
background.png
/application
styleInput2.less "url(../site/background.png)"
The gulp task:
gulp.task(filename, function () {
return gulp.src(files)
.pipe(sourcemaps.init())
.pipe(less())
.pipe(minifyCss({ relativeTo: './compiled' }))
.pipe(concat(filename))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./compiled'));
});
The output, with broken URLs. Note the multiple defects. Although the CSS is raised a directory level relative to the required assets, an additional parent directory has been added (!). Also, one of the URLs has had a hard asset folder name changed (!). Very strange:
/compiled
styleOutput1.css "url(../../compiled/logo.png)"
styleOutput2.css "url(../../site/background.png)"
My apologies for continuing the voodoo, but here is my working gulp pipe:
.pipe(minifyCss({ relativeTo: './compiled', target: './compiled' }))
And the correct output:
/compiled
styleOutput1.css "url(../assets/site/logo.png)"
styleOutput2.css "url(../assets/site/background.png)"
I personally use gulp-minify-css and specify the relativeTo attribute.
gulp.task('css', function() {
gulp.src('./assets/css/main.css')
// Here I specify the relative path to my files
.pipe(minifyCSS({keepSpecialComments: 0, relativeTo: './assets/css/', processImport: true}))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('./assets/css/dist/'))
.pipe(notify({
"title": "Should I Go?",
"subtitle": "Gulp Process",
"message": '<%= file.relative %> was successfully minified!',
"sound": "Pop",
"onLast": true
}));
});
If that doesn't work for you, they have a lot of other parameters to rebase URLs : https://github.com/jakubpawlowicz/clean-css#how-to-use-clean-css-programmatically
Notably:
rebase - set to false to skip URL rebasing
relativeTo - path to resolve relative #import rules and URLs
restructuring - set to false to disable restructuring in advanced
optimizations
root - path to resolve absolute #import rules and rebase relative
URLs
Related
I have this folder structure:
sass/main.sass
css/main.css
js/...
img/...
I want the sass output to go to the css folder, but each time I run sass watcher it creates a new css file within the sass directory among sass files.
Thx for information about using 'Live SASS Compiler' in VS Code.
To set special otuput pathes to your project you need to add the settings for output pathes to the settigns.json of your project:
File: `projectDIR/.vscode/settings.json'
Example for setting the save pathes to output directory:
"settings": {
// output: generate files to ...
// ~ = path starts relative from scss-file
"liveSassCompile.settings.formats":[
{
"format": "expanded",
"extensionName": ".css",
"savePath": "~/../assets"
},
// ad a compressed version
{
"format": "compressed",
"extensionName": ".min.css",
"savePath": "~/../assets"
}
// optional: add more outputs ...
],
}
See also official example in web: https://github.com/ritwickdey/vscode-live-sass-compiler/blob/master/docs/settings.md
Additional hint:
VERSION OFF 'LIVE SASS COMPILER' MAY BE OUTDATED
The actual commmon used Extension Live Sass Compiler is not longer supported (for years now). It uses an outdated SASS Version. The most recent features like #use are not supported in that version. You use that outdated version if author is 'Ritwick Dey'.
But there is an active supported fork with same name 'Live SASS Compiler' build by 'Glenn Marks'. As fork it works the same way and the settings are almost the same. Or you can use another actual compiler which is faster as you can use an direct installed SASS Version on your system. In that case you need to change the settings for your project.
Information about that you will find here:
https://stackoverflow.com/a/66207572/9268485
Updated: Correction name of author of supported extension 'Live SASS Compiler' to correct identification of extension.
Go to path: C:\Users\your user\AppData\Roaming\Code\User\settings.json
and change there the "liveSassCompile.settings.formats" section
for example:
the parameter : "savePath": "/Python/CSS",
For a new project I am bound to keep things webpack-only, and thus need to find a way to efficiently compile our stylesheets. Basically in a very gulh-ish way:
gather all less-files including glob-patterns like src/**/*.less (css order may be arbitrary)
also allow import of css files like, say ../node_modules/vendor/**/*.css or 3rdparty/master.less
(If I have to setup a bogus.js entry point for that, fine...)
And with all of that, a typical gulp workflow:
transpile less to css
merge (concat) less and css
have cssnano do its optimization job, with specific css nano options like e.g. orderedValues: false, normalizeWhitespace: true ...
write styles.css as final output
And of course:
have source-maps survive that chain for a styles.css.map
efficient watching and the usual lazy/incremental compilation (as gulp and webpack have it)
Something I do not need is css modules (css imported into node modules for 'scoped' use, coming out as hash-scoped selectors...)
How can a 'typical' less|css-processing toolchain be done in Webpack?
This SO question has my first attempt where I got stuck in config hell right in the middle after combining...
considerations so far (helpful or not)
I know, to webpack, any ressource including css or even font and images is a "module"... Rather than merging my css 'modules' with with actual js (only to later painstakingly separate them again later again), it might be wiser, to have an entry point cssstub.js in parallel – also known as multi-compiler mode.
But that's really, where my wisdom ends... doing a sequence of $things on a set of files in webpack seems really hard (unless it's a connected javascript module graph). I did find something on globbing, but that's not enough (merge css, cssnano,...) and mostly I simply can't glue the pieces together...
I have used gulp to build less and create corresponding maps like below:
First step compiles less and generated css in tmp folder
gulp.task('compile-less', function () {
gulp.src('./*.less') // path to your file
.pipe(less().on('error', function(err) {
console.log(err);
}))
.pipe(gulp.dest('./tmp/'));
});
Second step minifies generated css and create map files
gulp.task('build-css', ['clean'], function() {
return gulp.src('./tmp/**/*.css')
.pipe(sourcemaps.init())
.pipe(cachebust.resources())
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./compiled/css'));
});
If you want you can add additional step to conact generated css.
This is an interesting question, I've already searched Google so my hopes of reaching someone with an answer are slim.
I'm building a Grunt project, everything is great with my project except for one little thing I just noticed regarding relative paths ( ../../ ) when using the Assemble site generator. I am using a layout file in my project, fyi.
I need to use relative paths to link to files that are two levels lower than the root level of my Grunt project. But when I run my build the output HTML is resolving the relative paths to root.
For example, my HTML code in the dev file...
Hotels
is resolved to the following in the build file...
Hotels
It completely ignores the "../../" when I need that relative path to stay. I eventually plan on dumping this build folder into another project and taking advantage of it's resources that reside two levels lower than this build.
Any help is appreciated. So the gist of my questions... I want to maintain "../../" relative paths in my output HTML files after I run the Assemble task.
Here is the assemble task I've created...
assemble: {
options: {
layoutDir: './templates/layouts',
data: './templates/app/json/**/*.{json,yml}',
flatten: true
},
main: {
options: {
layout: './templates/layouts/default.html',
partials: './templates/app/partials/**/*.html'
},
src: './templates/app/*.html',
dest: './_build/'
}
}
I write Sass and use grunt-pleeease to inline #includes etc.
Unfortunately pleeease inlines its source map and ignores the existing one.
The source map file from sass is in the same folder as the css I pass to pleeease (main.css and main.css.map)
Is there a way to tell pleeease to use the existing source map and extend it?
I've also run into this problem. Currently, the pleeease grunt task doesn't write out the external source map even if you select the correct options. You can edit the task to make it do this anyway. I've submitted a pull request to the project on GitHub for this fix.
Note that I still had to specify the in and out options (pleeease gets the location of the original source map from the css file's sourcemap comment; you can specify this manually also using the prev option for sourcemaps, just note that you have to set that option to the contents of the sourcemap file, not the path of the sourcemap file--grunt.file.read() will be of use there):
pleeease: {
dist: {
options: {
in: 'build/styles/styles.css',
out: 'public/styles/styles.min.css',
sourcemaps: {
map: {
inline: false,
sourcesContent: true
}
}
},
files: {
'public/styles/styles.min.css': 'build/styles/styles.css'
}
}
},
Until this fix is implemented into the master branch and published on NPM, you can use the GitHub address of my pull request branch in your package.json to get the fix (please note that I will eventually remove this branch if my pull request is accepted or the fix is achieved in some other way):
"grunt-pleeease": "zeorin/grunt-pleeease#sourcemap-external",
I'm currently setting up grunt-usemin for our project but I'm running in a small issue with the cssmin task.
Our project depends on a few external libraries, some which bring a long some extra assets (like images or fonts). The problem is these libraries do not have the same folder structure.
This is an example of the different folder structures
lib
|--lib1
| |--style1.css
| +--image1.png
+--lib2
|--styles
| +--style2.css
+--images
+--image2.png
In the index.html all the stylesheets are referenced and put inside a build block. As such, when the usemin task executes, the stylesheets of the libraries are concatenated in one minified file and put inside the output folder. The corresponding assets (images) are copied over to this output folder as well and flatened in the img folder. The output folder structure looks like
out
|--allstyles.min.css
|--image1.png
+--image2.png
As you can guess, the concatenated stylesheets has (in this example) two different relative URIs:
image1.png
..\images\image2.png
This is causing an issue where some of the images cannot be found. I need a solution to rebase all relative URIs to the out folder. I tried using the target and root options of the cssmin task but to no avail. Could someone point me to a correct configuration of this task or to another Grunt task that could achieve what I'm looking for?
Thanks in advance!
I have a grunt file in C:\web\project and CSS files in C:\web\project\www\css. The following snippet is from my grunt file and it rebases URLs correctly for me.
var cssFiles = [
'www/css/layout/Header.css',
'www/css/layout/Footer.css',
'www/css/vendor/chosen/chosen.css'
// ...
];
cssmin: {
concat: {
options: {
keepBreaks: true, // whether to keep line breaks (default is false)
debug: true, // set to true to get minification statistics under 'stats' property (see test/custom-test.js for examples)
noAdvanced: true, // set to true to disable advanced optimizations - selector & property merging, reduction, etc.
//relativeTo: 'http://online-domain-tools.com/'
noRebase: false, // whether to skip URLs rebasing
root: 'www'
},
nonull: true,
src: cssFiles,
dest: 'www/temp/application.css'
},
minify: {
options: {},
nonull: true,
src: ['www/temp/application.css'],
dest: 'www/temp/application.min.css'
}
},
// ...
grunt.registerTask('default', ['cssmin:concat', 'cssmin:minify']);
Can you post your gruntfile to compare it?
Related reading: https://stackoverflow.com/a/21415649/99256
look in the cssmin documentation/options:
rebase: set to false to skip URL rebasing
That solves the issue.