Компилировать файлы LESS с исходными картами
Как я могу скомпилировать файл LESS для вывода файла исходной карты (.css.map
) в дополнение к файлу CSS? Есть ли способ сделать это в обеих командной строке (NodeJS's lessc
) а на каких графических программах?
3 ответа
Обновление: новый кратчайший ответ
Документы были обновлены! По мере появления новых функций в LESS иногда документы немного отстают, поэтому, если вы ищете новейшие функции, вам, вероятно, все же лучше работать lessc
(см. более длинный ответ) и проверка того, что выскакивает из текста справки.
Короткий ответ
Вы ищете любое количество следующих параметров из командной строки:
--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
Когда я пишу это, я не знаю ни о каких параметрах графического интерфейса, которые генерируют карты (исходные карты были добавлены в LESS только в последние несколько месяцев) - извините, что у меня нет хороших новостей. Я уверен, что они добавят поддержку по мере их обновления в течение следующего года.
Более длинный ответ
Если вы запустите lessc из командной строки без каких-либо параметров, это даст вам все опции. (По моему опыту, это более актуально, чем их документация, поэтому, по крайней мере, оно укажет вам правильное направление.) Со всеми самыми последними картами.
Самый простой комбо для использования в dev --source-map-less-inline --source-map-map-inline
так как это даст вам ваши исходные карты, встроенные в ваш выходной CSS.
Если вы хотите добавить отдельный файл карты, вы можете использовать --source-map
который из my.less
будет выводить my.css
а также my.css.map
Для справки: когда я запускаю свою копию (v 1.6.1 на данный момент), я получаю
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.
Если командная строка вас не устраивает, Грант великолепен в этом. Вы можете настроить плагин grunt-contrib-less для генерации встроенных карт с такой конфигурацией:
less: {
options: {
sourceMap:true,
outputSourceFiles: true
},
lessFiles: {
expand: true,
flatten:false,
src: ['**/*.less'],
dest: ['dist/'],
ext: '.css',
}
},
Пример создания карты и файла CSS из файла Less
- Установите последнюю версию Node JS, перейдите в командную строку и запустите
npm install less
, Теперь менее успешно установлен - Перейдите в командную строку и перейдите в меньшую папку с файлами, которую мы собираемся создать.
Например, я собираюсь изменить HelloWorld [Less File]
В командной строке перейдите в C:\Project\CSS или укажите правильный путь в приведенной ниже команде.
Запустите следующую команду в командной строке
lessc HelloWorld.less HelloWorld.css --source-map=HelloWorld.css.map –verbose
Теперь CSS и файл Map генерируются в соответствующей папке.
Для получения дополнительной ссылки проверьте ссылку: royalarun.blogspot.com