- И снова.. Почему Gulp 4 не работает?
- Создание и использование Source Maps для css и js в GULP 4
- 1. Базовый пример вывода Source Maps для js-файла
- 2. Кастомизированный пример подключения Source Maps в js-файлах и в css-файлах
- Problem with gulp-sass ? Or gulp-autoprefixer ? Or gulp-sourcemaps ? #60
- Comments
- ByScripts commented Nov 8, 2014
- floridoo commented Nov 8, 2014
- thaiat commented Nov 9, 2014
- ByScripts commented Nov 9, 2014
- crocket commented Nov 17, 2014
- heikki commented Nov 17, 2014
- heikki commented Nov 17, 2014
- crocket commented Nov 17, 2014
- heikki commented Nov 17, 2014
- crocket commented Nov 17, 2014
- heikki commented Nov 17, 2014
- crocket commented Nov 18, 2014
- crocket commented Nov 18, 2014
- stevemao commented Nov 20, 2014
- fingermark commented Nov 30, 2014
- BowlingX commented Dec 18, 2014
- polarathene commented Jan 12, 2015
- polarathene commented Jan 12, 2015
- DallanQ commented Jan 13, 2015
- polarathene commented Jan 15, 2015
- swieder227 commented Feb 9, 2015
- heikki commented Feb 18, 2015
- stevemao commented Feb 18, 2015
- heikki commented Feb 18, 2015
- stevemao commented Feb 18, 2015
- HectorLS commented May 19, 2016
- В Gulp не запускается один таск при сборке, в чём загогулина?
- Gulp не работает (Node + npm + Gulp + PhpStorm) Конфликт версий?
И снова.. Почему Gulp 4 не работает?
Подскажите, пожалуйста. Почему это не работает?
Может кто-то взять к себе и протестировать?
https://github.com/KononovD/kononovD.github.io/tre.
тут сам gulpfile.js и package.json
Ошибка следующая
[22:37:09] Using gulpfile
\Desktop\testGulp\gulpfile.js
[22:37:09] Starting ‘default’.
[22:37:09] Starting ‘build’.
[22:37:09] Starting ‘clean:build’.
[22:37:09] Finished ‘clean:build’ after 2.01 ms
[22:37:09] Starting ‘html:build’.
[22:37:09] Finished ‘html:build’ after 13 ms
[22:37:09] Starting ‘scss:build’.
[22:37:09] ‘scss:build’ errored after 4.53 ms
[22:37:09] TypeError: dest.on is not a function
at DestroyableTransform.Readable.pipe (C:\Users\я\Desktop\testGulp\node_modules\readable-stream\lib\_stream_readable.js:564:8)
at DestroyableTransform.pipe2 (C:\Users\я\Desktop\testGulp\node_modules\gulp-plumber\index.js:72:14)
at C:\Users\я\Desktop\testGulp\gulpfile.js:82:10
at taskWrapper (C:\Users\я\Desktop\testGulp\node_modules\undertaker\lib\set-task.js:13:15)
at bound (domain.js:395:14)
at runBound (domain.js:408:12)
at asyncRunner (C:\Users\я\Desktop\testGulp\node_modules\async-done\index.js:55:18)
at process._tickCallback (internal/process/next_tick.js:61:11)
[22:37:09] ‘build’ errored after 23 ms
[22:37:09] ‘default’ errored after 26 ms
Мне почему-то кажется, что все дело в автопрефиксере..
И еще может кто объяснить в чем разница 2х наблюдателей? Они в самом низу, первый (закомментированный) не просит модуль «gulp-warch», а 2й просит.. В чем разница?
Спасибо.
Источник
Создание и использование Source Maps для css и js в GULP 4
Хотелось бы в двух словах рассказать, как настроить Source Maps для GULP 4, но не получится вырвать из контекста просто пару строк кода, поэтому разобью статью на 2 части. Первая будет с базовым кодом для Source Maps, а во второй части будет куча кода из рабочего проекта.
Source Maps нужны для проектов, где происходит сборка нескольких файлов в один, например, компиляция файлов scss в один файл main.min.css или конкатенация js-файлов в один scripts.min.js . Карты источников нужны для того, чтобы быстро вносить правки, и не искать в каком файле задано определенное правило или функция, особенно когда для сборки используются десятки файлов или различных библиотек.
Так будет выглядеть в инспекторе код без Source Maps:
Так будет выглядеть код с использованием Source Maps:
И по итогу, если нам нужно увеличить отступ снизу у элемента .icon , то нам не нужно искать по всем файлам scss где задано это правило, а с помощью карты источников видим, что данное правило указано в файле _general.scss на 44 строке.
Если вам это не нужно, то дальше можно не читать.
1. Базовый пример вывода Source Maps для js-файла
Где — plugin1() и plugin2() — это какие-то образные плагины, которые занимаются минификацией и конкатенацией js-файлов, например.
Дальше будет много кода из рабочего примера, будет использоваться scss, сборка, минификация, конкатенация и т.д.
2. Кастомизированный пример подключения Source Maps в js-файлах и в css-файлах
Задача для компиляции файла main.min.css с Source Maps
Задача для конкатенации файла scripts.min.js с Source Maps
Все классно, но есть одна проблема.
sourcemaps.write() — не указаны пути для файла *.map, значит карта источников будет записана внутри файла в самый конец, тем самым увеличивая вес файлов более чем в два раза. Это не круто, но зато карты источников будут работать и в Chrome, и в Firefox.
sourcemaps.write(‘.’) — в таком формате source map запишется отдельным файлом в той же папке, что и основной файл, в формате main.min.css.map и scripts.min.js.map.
Проблема с лишним содержимым в виде карты путей решаема.
Source Maps нужны нам только во время разработки, поэтому при билде продашена просто удалим все комментарии из файлов .css и .js — а карта источников записана именно в виде комментария.
Это часть кода из моей таски ‘build’:
По итогу, на продакшене будут чистые минифицированные файлы без лишнего кода и комментариев.
Источник
Problem with gulp-sass ? Or gulp-autoprefixer ? Or gulp-sourcemaps ? #60
Comments
ByScripts commented Nov 8, 2014
There is a lot of issue about mixing gulp-sass and/or gulp-autoprefixer with gulp-sourcemaps.
I just spend 2 hours debugging to find out where the problem come from, and still no success.
But I finally noticed something (but still don’t know where the problem come from).
In this configuration:
The value of the key is $style.css , and it does not work
But in this configuration:
The value of the key is $style.scss , and it works
Because with the two configurations, _sourcemapContents in source-map-generator.js#360 has always a $style.scss key.
Hope this helps to resolve this issue, and to find if the problem come from sourcemap, sass or autoprefixer (or something else)
The text was updated successfully, but these errors were encountered:
floridoo commented Nov 8, 2014
Can you upload your test project somewhere, so I can try to debug? Thanks
thaiat commented Nov 9, 2014
ByScripts commented Nov 9, 2014
Don’t know if it’s related. In my sample I don’t import any other scss files, and I don’t get any error.
Just running npm install then gulp should do the work.
Hope this helps.
crocket commented Nov 17, 2014
heikki commented Nov 17, 2014
@ByScripts sourcesContent seems to work in your example if you update gulp-autoprefixer to 2.0.0.
heikki commented Nov 17, 2014
@crocket You’re using gulp-ruby-sass in your example. I get an error when running it. Which sass version do you have?
crocket commented Nov 17, 2014
@heikki I think the sass version is 3.4.8, and I suspect changes in gulp-ruby-sass broke gulp-sourcemaps. You should debug https://github.com/crocket/gulp-sourcemaps-example to confirm my suspicion.
heikki commented Nov 17, 2014
@crocket Your example is broken. 🙂
crocket commented Nov 17, 2014
@heikki How can I fix my example?
heikki commented Nov 17, 2014
@crocket That question is more suitable to StackOverflow 🙂
Your example doesn’t help reproducing this issue with sourcemaps because it doesn’t work at all.
crocket commented Nov 18, 2014
@heikki I updated https://github.com/crocket/gulp-sourcemaps-example so that it now uses Vagrant to set up its own environment in a new VM. Go check it up. It works.
Update 1. It seems gulp-ruby-sass is not meant to be compatible with gulp-sourcemaps and gulp-autoprefixer. Forget about my repository!
crocket commented Nov 18, 2014
Update. I successfully replicated the issue in a minimal test case at https://github.com/crocket/gulp-sourcemaps-example
stevemao commented Nov 20, 2014
I’m trying to add sourcemap feature to web-starter-kit (google/web-starter-kit#546) and I can’t generate correct result either.
Would you like to have a look at this please? Thanks
fingermark commented Nov 30, 2014
Anyone working on this?
BowlingX commented Dec 18, 2014
Have some more problems here, the trick with sourceMaps.loadMaps works, but source maps are not generated when having a more complicated setup like:
Project-A ( base.scss’) -> references e.g. bower_components/bootstrap-sass-official/assets/stylesheets/bootstrap And Project B references Project A (via bower_components/project-a/sass/base`)
Source maps stop working then, it only works when Project-A does not reference anything in bower_components
polarathene commented Jan 12, 2015
I’m not sure if I’m having the same problem. I’ve been looking into this for about 2 days now. I think gulp-autoprefixer is making a correct sourcemap between it’s input/output css files. gulp-sourcemaps and gulp-sass don’t seem to be the issue either. I’ve tried compiling my scss file with node-sass and it’s sourcemap feature, it seems to output a broken sourcemap regardless of settings.
I’ve come across an excellent visualizer tool. It would seem that the mappings for the scss file are correct but the output css file is incorrect, everything maps to 0. So the issue is likely node-sass or libsass?
You can see the scss/css I’ve been using to learn the gulp-sass/autoprefixer workflow with sourcemaps in the visualizer tool here . Note the bottom content identifying the mappings, each mapping starts with 0->, and as you can see in the css content on the right, it’s highlighting the first line only. Am I the only one getting a result like this? (autoprefixer aside).
polarathene commented Jan 12, 2015
I’ve looked further into this and am pretty sure the issue is related to libsass or node-sass with how they’re producing a sourcemap. I’ve manually corrected the scss-css sourcemap mappings, then used gulp-autoprefixer, mappings appear to be working and chrome/firefox dev tools are reporting the correct lines to the scss. You can see the scss/autoprefixer sourcemap here
Raised an issue on node-sass here, and just been notified it’s an issue with libsass which should be solved with libsass 3.2.
DallanQ commented Jan 13, 2015
Thank-you @ByScripts, your solution worked great for me! (I’m using gulp-sass)
polarathene commented Jan 15, 2015
@ByScripts gulp-sass was updated recently, mappings aren’t broken like before. If you’re using gulp-ruby-sass you should be fine with the alpha release if using external sources, embedded don’t seem to work. The only other issue with gulp-ruby-sass that prevents me using it is the file paths placed in sources of the sourcemap, I think this is only an issue with windows from what I’ve read.
I have code examples for both here
swieder227 commented Feb 9, 2015
npm update gulp-sass fixed the problem for me. Now working with gulp-sass , gulp-autoprefixer , and gulp-sourcemaps .
heikki commented Feb 18, 2015
I think this can be closed. @ByScripts’s sample tasks work identically with latest module versions.
stevemao commented Feb 18, 2015
I don’t think having .pipe(sourcemaps.write(
heikki commented Feb 18, 2015
@stevemao Then remove them 😄 Both tasks work now.
stevemao commented Feb 18, 2015
Thanks @heikki , for the reference web-starter-kit is already using this.
HectorLS commented May 19, 2016
Hi, i was reading that the new version fixed the problem, but i installed today
«gulp»: «^3.9.1»,
«gulp-autoprefixer»: «^3.1.0»,
«gulp-sass»: «^2.3.1»,
«gulp-sourcemaps»: «^1.6.0»,
And doesn’t work if i do:
But if i added the @ByScripts two MAGIC LINES works
When this would be fixed to don’t need that two lines. is like zero readable. :S
Источник
В Gulp не запускается один таск при сборке, в чём загогулина?
Здравствуйте! Впервые познакомился со сброщиком, Gulp-ом, вот как 2 дня уже, решил собрать первый конфиг, но не работает 1 таск при сборке, ниже расписал.
Сейчас я объединил 2 таска — scss и styles, всё работает, я изначально так делал, а потом подумал, если файл большой, то это он каждый раз будет запускать все плагины, после каждого изменения, поэтому решил разделить, чтобы только при сборке он занимался минификацией, подстановлением префиксов и т.п., и т.п., а до этого только работал препроцессинг. Или это не особо влияет? Я видел сборку от этого парня — https://markgoodyear.com/2014/01/getting-started-w.
Он сразу всё прогоняет препроц сасса и оптимизацию, на css-tricks там препроц и оптимизация отдельно.
Сильно ли влияет это на производительность, как лучше? И почему у меня не хочет выводить результат таска «styles».
Я сначала запускаю gulp build, оно копирует все папки из src в папку build, запускаю сервер в папке build, и делаю то, что нужно, останавливаю, набираю снова gulp build, чтобы всё ещё раз собрало, удаляя при этом папку build, но таск styles не фурычит. Спасибо!
Структура папки:
Источник
Gulp не работает (Node + npm + Gulp + PhpStorm) Конфликт версий?
C:\OpenServer\domains\localhost\projectgulp>node -v
v4.4.5
C:\OpenServer\domains\localhost\projectgulp>npm -v
2.15.5
C:\OpenServer\domains\localhost\projectgulp>gulp -v
[12:18:58] CLI version 3.9.1
[12:18:58] Local version 4.0.0-alpha.2
При выполнении команды
появляется ошибка и ничего не появляется в папке build (сюда должно всё билдится, прописано в файле gulpfile.js)
assert.js:90
throw new assert.AssertionError( <
^
AssertionError: Task function must be specified
at Gulp.set [as _setTask] (C:\OpenServer\domains\localhost\projectgulp\node_modules\undertaker\lib\set-task.js:10:3)
at Gulp.task (C:\OpenServer\domains\localhost\projectgulp\node_modules\undertaker\lib\task.js:13:8)
at Object. (C:\OpenServer\domains\localhost\projectgulp\gulpfile.js:171:6)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Liftoff.handleArguments (C:\Users\ShipGo\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:116:3)
Может конфликт версий Node и Gulp? Что делать? Как исправить?
- Вопрос задан более трёх лет назад
- 4351 просмотр
чтобы заработал пример в ролике нужна действительно gulp 4
Еще нада node-v4.4.5
v6.2.0 не катит)я думал поставлю себе самую новоую,а потом ловил ошибки постояно
C:\OpenServer\domains\localhost\projectgulp>node -v
v6.11.1
C:\OpenServer\domains\localhost\projectgulp>npm -v
3.10.10
C:\OpenServer\domains\localhost\projectgulp>gulp -v
[08:05:36] CLI version 3.9.1
[08:05:36] Local version 3.9.1
Я конечно сильно урезала gulpfile.js:
var gulp = require(‘gulp’), // Подключаем Gulp
less = require(‘gulp-less’), //Подключаем less пакет,
browserSync = require(‘browser-sync’), // Подключаем Browser Sync
concat = require(‘gulp-concat’), // Подключаем gulp-concat (для конкатенации файлов)
uglify = require(‘gulp-uglifyjs’), // Подключаем gulp-uglifyjs (для сжатия JS)
cssnano = require(‘gulp-cssnano’), // Подключаем пакет для минификации CSS
rename = require(‘gulp-rename’), // Подключаем библиотеку для переименования файлов
del = require(‘del’), // Подключаем библиотеку для удаления файлов и папок
imagemin = require(‘gulp-imagemin’), // Подключаем библиотеку для работы с изображениями
// pngquant = require(‘imagemin-pngquant’), // Подключаем библиотеку для работы с png
// cache = require(‘gulp-cache’), // Подключаем библиотеку кеширования
autoprefixer = require(‘gulp-autoprefixer’);// Подключаем библиотеку для автоматического добавления префиксов npm install gulp-uglifyjs —save-dev
Источник