cssmin grunt plugin generates incorrect source urls in sourcemap - css

cssmin grunt plugin grunt-contrib-cssmin trims leading slash in css sourcemap sources url, thus making css mapping incorrect. Meanwhile after editing sourcemap file by hand (adding leading slash to each source url) everything seems to be mapped correctly. Original sourcemap file is taken from annotation in original css (unminified), which is generated correctly by other grunt plugins.
My file structure:
web (resource root)
├─css
│ └─..(css files)
└─less
└─..(less files)
Sourcemap of original (unminified) css – sources urls are correct. Generated by grunt-contrib-less and grunt-autoprefixer respectively:
{"version":3,"sources":["/less/base/normalize.less","/less/base/boilerplate.less"...
Sourcemap of minified css – leading slashes for source files disappeared. Generated by grunt-contrib-cssmin:
{"version":3,"sources":["less/base/normalize.less","less/base/boilerplate.less"...
Part of my gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
cssmin: {
options: {
shorthandCompacting: false,
sourceMap: true,
roundingPrecision: -1
},
target: {
files: {
'web/css/style.min.css': 'web/css/style.css'
}
}
}
});
};

By now I solved this problem with grunt-string-replace plugin. I configured my gruntfile.js so that it adds leading slashes to source files in sourcemap:
module.exports = function(grunt) {
grunt.initConfig({
'string-replace': {
dist: {
files: {
'web/css/style.min.css.map': 'web/css/style.min.css.map'
},
options: {
replacements: [{
pattern: /"([^"])*(less\/)/g,
replacement: '"/less/'
}]
}
}
}
// other code
});
};
Well, it's a hack, because it requires additional grunt plugin. But it solved the problem.

Related

How do I generate sourcemaps for Uglified files using Grunt?

I have a Grunt project that uses both Browserify and Uglify. Here are the core bits of it:
browserify: {
myapp: {
options: {
transform: ['babelify'],
browserifyOptions: {
debug: true
},
},
src: 'src/index.js',
dest: 'build/myapp.js'
}
},
uglify: {
options: {
sourceMap: true,
banner: bannerContent
},
target: {
src: 'build/myapp.js',
dest: 'build/myapp.min.js'
}
},
It seems to generate a myapp.min.js.map file but it no longer has the raw sources in the source-map that existed prior to the Browserification.
Here's what the resultant source-map file contains:
{
"version":3,
"sources":[
"myapp.js"
],
"names":[
...
...
...
],
"mappings":".........",
"file":"myapp.min.js"
}
I've tried using the uglifyify transform for Browserify but that does not seem to generate as small files as the Uglify task.
I've also bumped all my dependencies to the latest but I haven't been able to resolve this issue.
grunt-contrib-uglify has a sourceMapIn option that allows you to specify the location of an input source map file from an earlier compilation - which in your scenario is the browserify task.
However, whilst setting browserifyOptions: { debug: true } in your browserify task does generate an inline source map in the resultant .js file (i.e. in build/myapp.js), the crux of the problem is twofold:
We don't have an external source map file that we can configure the sourceMapIn option of the subsequent grunt-contrib-uglify task to utilize.
grunt-browserify doesn't provide a feature to create an external .map file, it only creates them inline (see here)
To address the aforementioned issue consider utilizing grunt-extract-sourcemap to extract the inline source map from build/myapp.js (i.e. from the output file generated by your browserify task) after it has been produced.
Gruntfile.js
The following gist shows how your Gruntfile.js should be configured:
module.exports = function (grunt) {
grunt.initConfig({
browserify: {
myapp: {
options: {
transform: ['babelify'],
browserifyOptions: {
debug: true
},
},
src: 'src/index.js',
dest: 'build/myapp.js'
}
},
extract_sourcemap: {
myapp: {
files: {
'build': ['build/myapp.js']
}
}
},
uglify: {
options: {
sourceMap: true,
sourceMapIn: 'build/myapp.js.map'
},
target: {
src: 'build/myapp.js',
dest: 'build/myapp.min.js'
}
}
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-extract-sourcemap');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Note the order of the tasks in your task list is important.
grunt.registerTask('default', ['browserify', 'extract_sourcemap', 'uglify']);
};
Explanation
First the browserify task is invoked which outputs a new file (i.e. build/myapp.js) containing your bundled JavaScript and an "inlined" source map info. If you were to inspect the content of build/myapp.js at this stage it includes something like the following at the end:
//# sourceMappingURL=data:application/json;charset=utf-8;base64, ...
Next the extract_sourcemap task is invoked. This essentially extracts the "inlined" source map info from build/myapp.js and writes it to a new file named myapp.js.map which is saved in your build directory.
The original "inlined" source map info in build/myapp.js is replaced with a link to the newly generated source map file, i.e. myapp.js.map. If you inspect the content of build/myapp.js you'll now notice the following at the end of the file instead:
//# sourceMappingURL=myapp.js.map
Lastly the uglify task is invoked. Notice how its sourceMapIn option is configured to read build/myapp.js.map, i.e the source map file we generated at step 2.
This task creates your desired build/myapp.min.js file containing; your minified JS, and a link to a newly generated source map file build/myapp.min.js.map.
Note The final resultant file (i.e. build/myapp.min.js) now correctly maps back to the original src/index.js file and any file(s) that index.js itself may have import'ed or require()'d

Using a flag for a specific folder in Grunt to build from

I would like to now if there is a way to load certain files from a certain folder when running Grunt.
Let's say I have a folder structure that looks like this:
[html]
[css]
[js]
[custom]
[X] x.css
[Y] y.css
[Z] z.css
I'm trying to build my website for client [X] and need to add some custom css to their x.css file and just load that one to test.
What I would love to be able to do is run my grunt task (right now it runs sass, jsx compiler and spins up a localhost server with livereload) and say grunt client-x.
Which then would load my x.css file and all content of that folder but not use touch the [Y] and [Z] folder at all.
Is this possible with a task runner?
So I looked at Grunt dynamic dest location sass which seemed to solve my problem initially but I couldn't really get it to work the way I wanted to and it muddled up my existing grunt tasks I had already set up.
But then I found grunt options - this parameter solved all my problems. Grunt file below:
module.exports = function(grunt) {
var theme = grunt.option('theme')
grunt.initConfig({
concat: {
options: {
separator: 'rn'
},
dist: {
files: {
'js/script.js': 'themes/' + theme + '/js/custom.js'
}
}
},
watch: {
sass: {
files: ['themes/' + theme + '/**/*.{scss,sass}', 'themes/' + theme + '/_partials/**/*.{scss,sass}', 'sass/**/*.{scss,sass}', 'sass/_partials/**/*.{scss,sass}', 'themes/' + theme + '/js/custom.js'],
tasks: ['sass:dist', 'shell:upload', 'concat:dist'],
options: {
livereload: true,
},
},
livereload: {
files: ['*.vm', 'js/*.{js,json}', 'css/*.css','images/*.{png,jpg,jpeg,gif,webp,svg}', 'themes/' + theme + '/js/custom.js'],
options: {
livereload: true,
debounceDelay: 2000
}
}
},
sass: {
options: {
sourceMap: true,
outputStyle: 'nested'
},
dist: {
files: {
'css/lyria.css': 'themes/' + theme + '/styles.scss'
}
}
},
shell: {
options: {
stdout: true,
stderr: true
},
upload: {
command: './theme-uploader.sh'
}
},
})
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-shell');
grunt.registerTask('default', [
'sass:dist',
'concat',
'shell:upload',
'watch'
]);
};
As you can see the theme parameter is used as a argument for the grunt default task which then compiles the correct files to the correct place. When I run grunt --theme=x it watches and compiles the corresponding folders in that specific directory as set up by my different tasks.
The reason for this setup is that I'm developing and maintaining different child themes for different clients in the same repository. I need to be able to generate a client specific jar with their corresponding stylesheets and custom js.
This way I get to keep all my directories in the same repo and just specify when running my grunt task which client folder to get the css from.

Keeping LESS sourceMaps for minified css with cssmin

My LESS files are compiled with grunt-contrib-less and corresponding grunt task with the following config:
module.exports = {
options: {
sourceMap: true,
sourceMapFilename: 'Content/styles/e-life.css.map'
},
compile: {
files: {
'Content/styles/e-life.css' : 'Content/styles/common.less'
}
}
}
Then I procced with cssmin for output css file. I get it minified, but I want to bind source maps from the previous step for the minified css.
module.exports = {
options: {
sourceMap: 'Content/styles/e-life.css.map'
},
all: {
files: {
'Content/styles/e-life.css': ['Content/styles/e-life.css']
}
}
}
The task fails if I mention source map path in options.sourceMap. I see the following in css-clean docs:
sourceMap - exposes source map under sourceMap property, e.g. new CleanCSS().minify(source).sourceMap (default is false) If input styles are a product of CSS preprocessor (Less, Sass) an input source map can be passed as a string.
But i can not understand how to pass this string to the task. Is it even possible? How can I do this?
grunt-contrib-cssmin does NOT let you chain sourcemaps.
Its sourceMap option is true/false only, and will generate a map from the minified css to the original css, not to the original Less, sorry.
Considering that source mapping is useful mainly for debugging, I would suggest:
do not use cssmin in your development environment, that way you get mapping from css to your Less files if needed.
use cssmin without mapping for production.
You could also avoid the Grunt cssmin task and use the Less compression with compress option.
module.exports = {
options: {
compress: true,
sourceMap: true,
sourceMapFilename: 'Content/styles/e-life.css.map'
},
compile: {
files: {
'Content/styles/e-life.css' : 'Content/styles/common.less'
}
}
}
https://github.com/gruntjs/grunt-contrib-less#compress

Grunt CSS import and paths

I have the following setup in Grunt for the concat and minification of my projects css
cssmin: {
options: {
},
concat: {
files: {
'dist/app.css': [
'tmp/*.css',
'app/theme/css/vendors/fontello.css',
'app/theme/js/vendors/revolution/css/settings.css',
'app/theme/css/styles.css',
'app/theme/css/media-queries.css',
'app/app.css'
]
}
},
min: {
files: [{
src: 'dist/app.css',
dest: 'dist/app.css'
}]
}
},
It works fine with the exception that, as far as I can tell its removed the following import statement
#import url("http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic");
And all 3rd party css files have relative image paths which are not resolved. I can see cssmin uses clean css which should be able to help handle these issues but after hours of searching and reading the docs I can't any clear examples or doucmentation on how to configure the above to solve this?
I used Ze Rubeus suggestion of moving my font import statement into the HTML instead (a little annoying as it means modifying a 3rd party css file). But I found the option for fixing the css paths which is
rebase: true,
relativeTo: './'
My cssmin configuration now looks like
cssmin: {
options: {
rebase: true,
relativeTo: './'
},
concat: {
files: {
'dist/app.css': [
'tmp/*.css',
'app/theme/css/vendors/fontello.css',
'app/theme/js/vendors/revolution/css/settings.css',
'app/theme/css/styles.css',
'app/theme/css/media-queries.css',
'app/app.css'
]
}
},
min: {
files: [{
src: 'dist/app.css',
dest: 'dist/app.css'
}]
}
}
And everything is working :)
You have to change all you import PATH depend on this directory 'dist/app.css'
And instead of css font import I advice you to use the HTML link like the following
<link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic' type='text/css'>
make sure to change all url Path's on these directory's :
'tmp/*.css',
'app/theme/css/vendors/fontello.css',
'app/theme/js/vendors/revolution/css/settings.css',
'app/theme/css/styles.css',
'app/theme/css/media-queries.css',
'app/app.css'
depend on this output 'dist/app.css': because there is no task in gruntjs who correct the import Path in css files for you !
regarding your code the watch task need's to be something like so :
watch: {
css: {
files: ['tmp/*.css',
'app/theme/css/vendors/fontello.css',
'app/theme/js/vendors/revolution/css/settings.css',
'app/theme/css/styles.css',
'app/theme/css/media-queries.css',
'app/app.css'],
tasks: ['concat','cssmin'],
options: { spawn: false }
}
},
And execute this command grunt watch in your terminal to keep automatically tracking for changes in these files and apply these tasks .

How to set CSS Source Map output destination when grunt-contrib-less is used

I am using grunt-contrib-less for compiling less files.
I have grunt locally installed at root of project folder.
The css files are located at qa1/avinash/html5/phase1/css/ path from root of project folder.
So this is the path i am specifying for cwd (current working directory), src and dest parameters of the grunt-less task. there are no issues in compilation of css and source map.
The only issue i face is that the source map is generated in the same folder of gruntfile. but my generated css is at the dest path i specified. since the css and source map are at different locations i have to manually edit the less path references in source map and bring it to the generated css directory. or use sourceMapURL to specify the source map location ../../../../../style.css.map(backwards). Both ways are not convenient.
So can anyone help me how to specify the source map output destination path like we specify for destination path for generated css something like
sourceMapDest: 'qa1/avinash/html5/phase1/css/'
--
currently used Gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
less: {
options: {
sourceMap:true,
sourceMapFilename: "style.css.map",
sourceMapURL: '../../../../../style.css.map'
},
src: {
// no need for files, the config below should work
expand: true,
cwd: "qa1/avinash/html5/phase1/css/",
src: "style.less",
dest: "qa1/avinash/html5/phase1/css/",
ext: ".css"
}
},
watch: {
js: {
files: ['qa1/avinash/html5/phase1/css/'],
tasks: ['default'],
}
}
});
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['less']);
};
The sourceMapFilename option may include a path part as well.
I.e. just change it to:
sourceMapFilename: "qa1/avinash/html5/phase1/css/style.css.map"

Resources