Gulp 4: Built-in Sourcemaps
One really cool feature on the Gulp 4 roadmap is the inclusion of native sourcemaps. A commit roughly two weeks ago at the vinyl-fs package makes this possible now. Instead of using the gulp-sourcemaps package directly, you can use a flag in gulp.src . Gulp takes care of the rest:
gulp.dest takes care of saving those sourcemaps. So with every gulp.dest command, you get new sourcemaps for your output.
Under the hood, Gulp still uses the gulp-sourcemaps package. It’s just a much nicer and more direct way of addressing them. Still, your plugins have to “understand” Sourcemaps.
Beta Installation #
At the moment, this is still in Beta. To test it, you have to have Gulp 4 installed:
Enter the node_modules/gulp/ directory, and install the current vinyl-fs package.
You won’t have to do this anymore once Gulp 4 is public on NPM.
gulp-sourcemaps #
There might be some occasions where you still would need the old plugin. For example, you want to name your source directories to make them easier findable inside your Dev tools. For that, you still have to use the original plugin:
It is also necessary, if you want to combine it with other sourcemaps, like those generated by Browserify:
But since it has the same codebase, you should be fine using them. This is also one of those things that Gulp 4 was constructed on: Things that have proven to be useful, if not mandatory in the past are now getting into core, but still as extractable and reusable as any part of Gulp.

Interested in Gulp and Front-End Tooling? Check out my book on Gulp, Yeoman and Bower and get 39% off with the code 39baumgar
Javascript Debugging Made Easier with Sourcemaps
Updated: Add clean task that uses rimraf to delete the bundle.min.js file if it already exist. Without this it would just append to the existing bundle.min.js file.
When you release your web site to production, you should minify and concatenate your javascript files. You will have much better performance by doing this but unfortunately debugging becomes difficult with the minified code as it shortens all of the variable and method names. Luckily there is a simple solution to tell the browser developer tools to use the original javascript files when debugging the code, called source maps.
Sourcemaps bacically are a way to map the combined/minified file back to the original file. As part of the minification process you generate a source map which holds the information about your original files. The developer tools will then parse the source map and make it appear as though you’re running unminified and uncombined files.
Creating Sourcemaps
To generate the sourcemaps we are going to gulp with the gulp-concat, gulp-uglify, and gulp-sourcemaps modules. If you are not familiar with gulp, it is basically a javascript build system that allows you to write code to automate tasks.
Install node.js if you don’t have it installed already.
Install Gulp and the Gulp modules that we need.
Create a file called gulpfile.js if you don’t already have one.
Add the required gulp modules to the gulpfile.js.
Create the input paths variable to hold what files we should minify/concatenate. I keep my files in the www folder. The ! in the 2nd input path means to exclude this path. I typically keep my vendor skips like angular, ionic, jquery, etc in the lib folder, so I don’t want to minify those scripts again.
Create the output path variable to tell gulp where to output the minified file.
Now we need to create the actual gulp task that does the minification and source map creation. This tasks takes the inputPaths.javscript files, combines them, minifies them, creates the source maps and save it all as a file called bundle.min.js. By default the gulp.dest call will append the minified text to the bundle.min.js instead of overwriting it. Instead we need to call the clean task task first which will delete the minified file if it already exist.
Create the clean task
Once the task is created, we want to setup a gulp watch to regenerate the file when any of the javascript changes.
Finally, we are going to create a default task to run the build-js task we created. The default task will typically what you want to run anytime you start up the web server.
Running Task
Open a command prompt or terminal.
Navigate to the directory that contain the gulpfile.js we created.
Run the following command:
If it worked successfully, you should have a minified file in your www/js folder.
To use the file, open up the index.html file and remove all of your javascript script tags that reference your js files in the www folder and replace it with a single script tag that references the www/js/bundle.min.js file. Make sure to leave any vendor script tags.
Enabling Sourcemaps in Chrome Developer Tools
Now that we have the source maps generated, we have to tell the Chrome Developer Tools to enable the source maps.
Open Google Chrome.
Open the Developer Tools.

Click on the Setting Cog.

Scroll down in the General Settings under you see the Sources section and ensure that the “Enable JavaScript source maps” is checked.

Click on the X in the upper right of the Settings windows to close it.
Now view your web site in the browser to make sure everything is still working.
- Note: If you are using Angular, you have to make sure that you use the minification safe syntax for the dependency injection. See the next section for examples.
- Note 2: If you are using the Ionic Framework, the default templates (blank, tabs, sidemenu) do not use the Angular minification safe syntax. You will need to modify the template after you generate your application.
Angular Minification Safe Syntax
If you are using the AngularJs framework it does a lot of dependency injection. Out of the box, if you just pass in your arguments to the different functions, it is not minification safe. There are a couple of easy ways to make it minification safe with a minimal amount of code changes.
Option 1: $inject method
Option 2: [] syntax. You start the 2nd parameter with a [, put your list of dependencies as string, your function to run and then the closing ].
Создание и использование 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’:
По итогу, на продакшене будут чистые минифицированные файлы без лишнего кода и комментариев.
Sourcemaps
It looks like your browser may not support the H264 codec. If you’re using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.
Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let’s us get back to making more videos :). But as always, please feel free to message us.
To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video
- Script
- Conversation
- Versions
Check out the source style.scss file. We’re giving an element a fancy cursive font on lines 4 and 5. And that’s what makes the Dinosaurs text look so awesome.
But if we inspect that element, it says the font is coming from styles.css line 2. Dang it! The browser is looking at the final, processed file. And that means that debugging CSS is going to be an absolute nightmare.
What I really want is the debugger to be smart enough to tell me that this font is coming from our styles.scss file at line 4. Such mysterious magic goodness exists, and it’s called a sourcemap.
Using gulp-sourcemaps
Like with everything, this works via a plugin. Head back to the plugins page and search for gulp-sourcemaps. There’s the one I want!
Step 1 is always the same — install with npm . So:
Awesome! Next, copy the require statement and put that on top:
| var gulp = require ( 'gulp' ); |
| var sass = require ( 'gulp-sass' ); |
| var sourcemaps = require ( 'gulp-sourcemaps' ); |
| . lines 4 — 12 |
This plugin is great. First, activate it before piping through any filters that may change which line some code lives on. So, before the sass() line, use pipe() with sourcemaps.init() inside. Then after all those filters are done, pipe it again through sourcemaps.write(‘.’) :
| . lines 1 — 4 |
| gulp. task ( 'default' , function () < |
| gulp. src ( 'app/Resources/assets/sass/**/*.scss' ) |
| . pipe (sourcemaps. init ()) |
| . pipe ( sass ()) |
| . pipe (sourcemaps. write ( '.' )) |
| . pipe (gulp. dest ( 'web/css' )); |
| >); |
Ok, let’s try it! At the terminal, run gulp . and hope for the best!
Cool — no errors. And now, the generated styles.css has a neighboring file: styles.css.map ! That’s what the . did — it told Gulp to put the map file right in the same directory as styles.css , and the browser knows to look there.
Time to refresh the page again. Inspect the element again. Now it says the font comes from styles.scss on line 4. This is a huge deal guys. We can do whatever weird processing we want and not worry about killing our debugging.
Sourcemaps Support
Of course, this all works because gulp-sourcemaps and gulp-sass work together like super friends. If you look at the sourcemaps docs, they have a link on their wiki to a list of all super-friend gulp plugins that play nice with it. We’ll use a couple of these later.