Everton Agner Everton Agner - 5 months ago 11
Javascript Question

Moving out of bundled Javascript during local debugging

Current tasks on gulpfile.js on my frontend app included a

serve
task on which it did the following:


  • Processed less files

  • Bundled all javascripts into dist/bundle.js

  • Uglified dist/bundle.js



Since that made things hard for local debugging, I've created a new
serve:debug
task that, at first, did not uglified
dist/bundle.js
.

gulp.task('serve:debug', ['less', 'bundle', 'watch'], function () {
runServer('http://localhost/app/login.html')
});


That works and makes me able to at least debug human readable javascript code. But all files are still bundled together because my application explicitly imports
dist/bundle.js
on index.html:

<script src="dist/bundle.js"></script>


If I remove
bundle
task on
serve:debug
, application will not be able work reach
dist/bundle.js
anymore.

Question: What are the best practices to work around this when importing javascript files?

Answer

You can use gulp-sourcemaps to write an inline sourcemap into your bundle. This will cause the browser's developer tools to display source as if it were in the original source files despite actually being served in a bundle.

This would look something like:

var sourcemaps = require('gulp-sourcemaps');

gulp.task('bundle', function() {
  gulp.src('src/**/*.js')
    .pipe(sourcemaps.init())
      .pipe(bundle())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist'));
});

There's a good general overview of how source maps work here: http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/

Comments