inline less source map compiled from node code - css

The project I'm working on is using code to run the less compiler.
I'm having trouble adding an inline source map to the compiled css from my less files.
From node we are running the following code:
var less = require('less'),
options = {
strictMath: true
};
less.render(data, options, function(err, css) {
callback(err, css);
});
Is there an option I can add?
I've tried adding sourceMap: true and outputSourceFiles: true without success.

Since Less v 1.5 the compiler has support for the following options
--source-map[=FILENAME] Outputs a v3 sourcemap to the filename (or output filename.map)
--source-map-rootpath=X adds this path onto the sourcemap filename and less file paths
--source-map-basepath=X Sets sourcemap base path, defaults to current working directory.
--source-map-less-inline puts the less files into the map instead of referencing them
--source-map-map-inline puts the map (and any less files) into the output css file
--source-map-url=URL the complete url and filename put in the less file
The sourceMap and outputSourceFiles options you have tried seems to related to grunt-contrib-less, see: https://github.com/gruntjs/grunt-contrib-less

Related

How can I export multiple files while compiling less to css from gulp?

Right now, I am using Gulp for a project which is basically a CSS framework. The way I am doing it right now is, I #import all the other .less files in a single app.less and then pass it to the Gulp task:
// Compile
gulp.task("compile", function() {
return gulp
.src("source/app.less")
.pipe(less())
.pipe(concat("framework.edge.css"))
.pipe(gulp.dest("./dist"))
.pipe(
autoprefixer({
browsers: ["last 4 versions"],
cascade: false
})
)
.pipe(concat("framework.css"))
.pipe(gulp.dest("./dist"))
.pipe(sourcemaps.init())
.pipe(
uglify({
maxLineLength: 80,
UglyComments: false
})
)
.pipe(concat("framework.min.css"))
.pipe(sourcemaps.write("./"))
.pipe(gulp.dest("./dist"));
});
This works totally as expected. The stylesheets are first compiled and the exported as app.edge.css, then it is passed through autoprefixer, exporting framework.css and then the minification process.
The problem is, now I want to export each stylesheet as a separate module, such as
grids.css
scaffolding.css
and so on...
How can I achieve this? I am actually not getting what logic to apply.
Use globbing
If a gulp tasks's src is x/**/*.less, the task will process all LESS files in x or any subfolder of x and will output each file separately in the dest, preserving the src's file structure.
To exclude a file or files, use !....
Learn the globbing rules in the Glob Primer, and test your pattern with the Glob online tester
Depending on your needs, you might want two tasks, one for outputting individual files and one for building the full framework.css.

My LESS sourceMap file is missing the "file" when run through grunt

When I run lessc --source-map=styles.map assets/less/00_style.less dest/assets/prod.css in the command line, everything is working. The styles.map file ends in:
...AV2rEF;EAAiB,aAAA","file":"dest/assets/prod.css"}
However, when I run grunt less, the styles.map is missing the "file" part and just ends in:
...AV2rEF;EAAiB,aAAA"}
This stops the SourceMap from working. What could be going wrong? My less config is as follows:
less: {
dist: {
options: {
sourceMap: true,
sourceMapFilename: 'styles.map'
},
files: [{
src : 'assets/less/00_style.less',
dest: 'dest/assets/prod.css'
}]
}
}
Short answer:
Add the following additional option to your less Task in Gruntfile.js:
...
options: {
...
sourceMapURL: '../../styles.map'
},
...
Long answer:
When running the lessc command via the CLI, (as per your example), notice the the following comment is written to the resultant prod.css:
/*# sourceMappingURL=../../styles.map */
However, when running the grunt task, (using your current config), the following comment is written into the resultant prod.css:
/*# sourceMappingURL=styles.map */
Note the missing ../../ - therefore prod.css can't find styles.map
This is why your SourceMap isn't working and not so much to do with the "file:" missing in styles.map when run via grunt. The .css file ultimately points to the .map file - not vice versa.
Even after running the lessc command via the CLI then deleting the "file:" part from styles.map you will find that the SourceMap still works in the browser. Indicating that the "file:" part, whether included in the .map file or not, has no effect on preventing the SourceMap from working.
Besides, as noted in the most recent proposed SourceMap spec (v.3) the "file:" part is optional:
Line 3: An optional name of the generated code that this source map is associated with.
Explicitly defining the sourceMapURL in your grunt Task options will entail having to keep a flat folder structure inside the dest/assets/ directory if you intend on using multiple .less files. (I.e. You'll need to avoid saving any resultant .css files in subfolders)

How to detect root files in LESS using gulp compilation

Here is the thing. I have following structure of my LESS files:
/less/root.less
/less/includes1/*.less (a lot of less files)
/less/includes2/*.less (a lot of less files)
I am using gulp to compile my LESS files. Source:
gulp.task('less', function () {
var combined = combiner.obj([
gulp.src('./less/**/*.less'),
less(),
gulp.dest('./www/dist/screen.css')
]);
// any errors in the above streams will get caught by this listener, instead of being thrown:
combined.on('error', console.error.bind(console));
return combined;
});
The problem is in the specified path. I understand this path ./less/**/*.less like this: Recursively go through all folders and compile all files that ends .less. Problem is that compiler wants to compile each file one by one and doesnt know that all files are included to my source.less. It doesnt look for root files and doesnt know what files are included parts and what are root files.
How do I tell LESS parser which files are root and which files are to be imported. In SASS it is specified via underscore in file name like this: _includedPart.scss.
Well you can use https://github.com/robrich/gulp-ignore. See: How can I use a glob to ignore files that start with an underscore?
var condition = '_*.less'; //exclude condition
gulp.src('content/**/*.less')
.pipe(gulpIgnore.exclude(condition))
In many situations you all your Less code into a single CSS file. Your main file(s) contain #import directive which point all other required Less files.

Gulp gulp-less and gulp-sourcemaps giving wrong sourceMappingURL

I have a gulp workflow with a simple less task like so:
gulp.task('less', function() {
gulp.src(source_less)
.pipe(sourcemaps.init())
.pipe(less({
sourceMap: true
}))
.pipe(sourcemaps.write())
.pipe(gulp.dest(dest_less));
});
I want the gulp-sourcemaps module to display source maps as inline comments in my CSS file.
But whenever gulp compiles my LESS, the gulp-sourcemaps isn't displaying a path to my source file.
Instead, it displays something like this:
/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2
VzIjpbIm1haW4ubGVzcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtFQUNJLG1DQUFBIiwi
ZmlsZSI6Im1haW4uY3NzIiwic291cmNlc0NvbnRlbnQiOlsibmF2IHtcclxuICAgIGJhY2tncm91bmQtY29
sb3I6IHllbGxvdyAhaW1wb3J0YW50O1xyXG59Il0sInNvdXJjZVJvb3QiOiIvc291cmNlLyJ9 */
I dramatically simplified my gulpfile, removing livereload, autoprefixer and such.
But even in this stripped down version I can't get the source URL to be right.
Been over this thing for quite some time now, any help would be very much appreciated!
You already have sourcemaps inline there. If you base64 decode what comes after sourceMappingURL=data:application/json;base64, you'll get this:
{"version":3,"sources":["main.less"],"names":[],"mappings":"AAAA;EACI,mCAAA","file":"main.css","sourcesContent":["nav {\r\n background-color: yellow !important;\r\n}"],"sourceRoot":"/source/"}
Try it yourself here: https://www.base64decode.org/
For those who stumble upon this post and are wondering how to get a separate file for the map that's is not in base64 format - you can pass a path relative to the destination.
For example:
.pipe(sourcemaps.write('./'))

Compile LESS files with source maps

How can I compile a LESS file to output a source map file (.css.map) in addition to a CSS file? Is there a way to do it on both command line (NodeJS's lessc) and on any GUI-based programs?
Update: New shortest answer
The docs have been updated! As new features hit LESS, sometimes the docs lag behind a bit, so if you're looking for bleeding-edge features, you're still probably better off running lessc (see longer answer) and checking what pops out of the help text.
http://lesscss.org/usage/
Short answer
You're looking for any number of the following options from the command line:
--source-map[=FILENAME] Outputs a v3 sourcemap to the filename (or output filename.map)
--source-map-rootpath=X adds this path onto the sourcemap filename and less file paths
--source-map-basepath=X Sets sourcemap base path, defaults to current working directory.
--source-map-less-inline puts the less files into the map instead of referencing them
--source-map-map-inline puts the map (and any less files) into the output css file
--source-map-url=URL the complete url and filename put in the less file
As I write this I'm not aware of any GUI options that generate maps (source maps were only added to LESS in the last few months) -- sorry to not have any better news. I'm sure they'll add support in as they update over the next year.
Longer answer
If you run lessc from the command line without any parameters it will give you all the options. (In my experience, this is more up to date than their documentation, so it'll at least get you pointed in the right direction.) with all the most recent map stuff included.
The easiest combo to use for dev is --source-map-less-inline --source-map-map-inline as that will give you your source maps embedded in your output css.
If you'd like to add a separate map file, you can use --source-map which, from my.less will output my.css and my.css.map
For reference: when I run my copy (v 1.6.1 at the moment) I get
usage: lessc [option option=parameter ...] <source> [destination]
If source is set to `-' (dash or hyphen-minus), input is read from stdin.
options:
-h, --help Print help (this message) and exit.
--include-path=PATHS Set include paths. Separated by `:'. Use `;' on Windows.
-M, --depends Output a makefile import dependency list to stdout
--no-color Disable colorized output.
--no-ie-compat Disable IE compatibility checks.
--no-js Disable JavaScript in less files
-l, --lint Syntax check only (lint).
-s, --silent Suppress output of error messages.
--strict-imports Force evaluation of imports.
--insecure Allow imports from insecure https hosts.
-v, --version Print version number and exit.
-x, --compress Compress output by removing some whitespaces.
--clean-css Compress output using clean-css
--clean-option=opt:val Pass an option to clean css, using CLI arguments from
https://github.com/GoalSmashers/clean-css e.g.
--clean-option=--selectors-merge-mode:ie8
and to switch on advanced use --clean-option=--advanced
--source-map[=FILENAME] Outputs a v3 sourcemap to the filename (or output filename.map)
--source-map-rootpath=X adds this path onto the sourcemap filename and less file paths
--source-map-basepath=X Sets sourcemap base path, defaults to current working directory.
--source-map-less-inline puts the less files into the map instead of referencing them
--source-map-map-inline puts the map (and any less files) into the output css file
--source-map-url=URL the complete url and filename put in the less file
-rp, --rootpath=URL Set rootpath for url rewriting in relative imports and urls.
Works with or without the relative-urls option.
-ru, --relative-urls re-write relative urls to the base less file.
-sm=on|off Turn on or off strict math, where in strict mode, math
--strict-math=on|off requires brackets. This option may default to on and then
be removed in the future.
-su=on|off Allow mixed units, e.g. 1px+1em or 1px*1px which have units
--strict-units=on|off that cannot be represented.
--global-var='VAR=VALUE' Defines a variable that can be referenced by the file.
--modify-var='VAR=VALUE' Modifies a variable already declared in the file.
-------------------------- Deprecated ----------------
-O0, -O1, -O2 Set the parser's optimization level. The lower
the number, the less nodes it will create in the
tree. This could matter for debugging, or if you
want to access the individual nodes in the tree.
--line-numbers=TYPE Outputs filename and line numbers.
TYPE can be either 'comments', which will output
the debug info within comments, 'mediaquery'
that will output the information within a fake
media query which is compatible with the SASS
format, and 'all' which will do both.
--verbose Be verbose.
If the command line doesn't suite you, Grunt is great at this type of thing. You can configure the grunt-contrib-less plugin to generate inline maps with a config like this:
less: {
options: {
sourceMap:true,
outputSourceFiles: true
},
lessFiles: {
expand: true,
flatten:false,
src: ['**/*.less'],
dest: ['dist/'],
ext: '.css',
}
},
https://github.com/gruntjs/grunt-contrib-less
Example to Create Map and CSS file from Less File
Install latest Node JS and go to command prompt and run npm install less, Now less installed successfully
Go to Command Prompt and move to less file folder that we are going to create
For e.g., I am going to change HelloWorld [Less File]
In Command prompt go to C:\Project\CSS or give the correct path in the below command.
Run following Command in Command Prompt
lessc HelloWorld.less HelloWorld.css --source-map=HelloWorld.css.map –verbose
Now CSS and Map file is generated in the respective folder.
For more reference check the link : royalarun.blogspot.com

Resources