Getting Started with GulpJS errors

I am going through the Getting Started with Gulp JS Book and there is an error in the code that I cannot correct nor find a solution in Dr. Google.

.pipe(devBuild ? noop() : htmlclean())

returns:

stripdebug = devBuild ? null : require(‘gulp-strip-debug’),
^

ReferenceError: Cannot access ‘devBuild’ before initialization
at Object. (C:\Users\riadk\Desktop\projectsamle\gulpfile.js:11:16)

Does anyone have an idea what is happening here and why this is broken. I cannot figure out why a tutorial from Sitepoint would give broken code…

Here is the full cli call:

riadk@RIADS-LAPTOP MINGW64 ~/Desktop/projectsample/src (master)
$ gulp css
[02:36:04] Working directory changed to ~\Desktop\projectsample
C:\Users\riadk\Desktop\projectsample\gulpfile.js:11
  stripdebug = devBuild ? null : require('gulp-strip-debug'),
               ^

ReferenceError: Cannot access 'devBuild' before initialization
    at Object.<anonymous> (C:\Users\riadk\Desktop\projectsample\gulpfile.js:11:16)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)     
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at execute (C:\Users\riadk\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\index.js:36:18)
    at Liftoff.handleArguments (C:\Users\riadk\AppData\Roaming\npm\node_modules\gulp-cli\index.js:201:24)
    at Liftoff.execute (C:\Users\riadk\AppData\Roaming\npm\node_modules\gulp-cli\node_modules\liftoff\index.js:201:12)

Hi,

Just to be sure, is this the book you mean?

If so, which is the section with the code that is giving you the error? It would be helpful if you could provide steps to reproduce the error you are having.

Anything is possible — a version mismatch, typo etc.

@James_Hibbard the link to the book is An Introduction to Gulp.js

The part that I am getting the error is under [HTML Tasks] The same issue will happen under the JavaScript tasks as well. It has something to do with the `.pipe devBuild ? noop html clean

Thanks!

Ok, ta. I’ll have a look.

Thank you!

There are a couple of typos in there which I’ll pass on to HQ to get fixed. Sorry about that.

I read up to the end of the HTML Task section and the following worked for me:

const gulp = require('gulp');
const noop = require('gulp-noop');
const newer = require('gulp-newer');
const imagemin = require('gulp-imagemin');
const htmlclean = require('gulp-htmlclean');

// development mode?
// const devBuild = (process.env.NODE_ENV !== 'production');
const devBuild = false;

// folders
const src = 'src/';
const build = 'build/';

// image processing
function images() {
  const out = `${build}images/`;
  return gulp.src(`${src}images/**/*`)
    .pipe(newer(out))
    .pipe(imagemin({ optimizationLevel: 5 }))
    .pipe(gulp.dest(out));
}

function html() {
  const out = `${build}html/`;
  return gulp.src(`${src}html/**/*`)
    .pipe(newer(out))
    .pipe(devBuild ? noop() : htmlclean())
    .pipe(gulp.dest(out));
}

exports.images = images;
exports.html = gulp.series(images, html);

This ran without error and minified my sample HTML file as expected.

Please note, I set the devBuild variable to false for testing purposes and also that I have a linter set to automatically lint the code, so this will also look a bit different from what’s in the book.

Could you give that a go and let me know how you get on.

That works, thanks. Could you explain a little more what exactly was wrong so I can try to fix it on the JS section as well. I’d like to know what the error was for future.

Thank you!

@James_Hibbard I figured it out. It mainly had to do with the src and build

Last issue I am running into.

On the CSS part, I got it to work but I then get this warning. According to Google its pretty common but no fixes.

Replace Autoprefixer browsers option to Browserslist config.
Use browserslist key in package.json or .browserslistrc file.

Using browsers option can cause errors. Browserslist config
can be used for Babel, Autoprefixer, postcss-normalize and other tools.

If you really need to use option, rename it to overrideBrowserslist.

Hey,

So the problem is that in Autoprefixer’s latest release, the browsers option is deprecated.

In gulpfile.js you need to do is change this:

autoprefixer({ browsers: ['last 2 versions', '> 2%'] }),

to this:

autoprefixer(),

Then in package.json, add the following key:

"browserslist": [
  "last 2 versions",
  "> 2%"
]

After that, things should work as expected.

To give it a test, you can copy this into main.scss:

.example {
  display: grid;
  transition: all .5s;
  user-select: none;
  background: linear-gradient(to bottom, white, black);
}

When you run gulp css, it should get transpiled to:

.example {
  display: grid;
  -webkit-transition: all .5s;
  transition: all .5s;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#000));
  background: linear-gradient(180deg, #fff, #000)
}

HTH

It works! Thanks so much!

I had mastered gulp 3 but for some reason 4 just kills my brain. Maybe because Im getting too old :smiley:

Thank you so much @James_Hibbard

1 Like

No worries :slight_smile:

@James_Hibbard I hate to keep bothering you but after everything is working there is one last issue and I will be done.

For some reason the sourcemap is outputting on the same file as the output css

// CSS processing
function css() {
  return gulp.src(`${src}scss/**/* `)
    .pipe(sourcemaps ? sourcemaps.init() : noop())
    .pipe(sass({
      outputStyle: 'nested',
      imagePath: '/images/',
      precision: 3,
      errLogToConsole: true
    }).on('error', sass.logError))
    .pipe(postcss([
      assets({ loadPaths: ['images/'] }),
      autoprefixer(),
      mqpacker,
      cssnano
    ]))
    .pipe(sourcemaps ? sourcemaps.write() : noop())
    .pipe(gulp.dest(`${build}/css`));
}

exports.css = gulp.series(images, css);

The follwing is the output for build/css/#app.css

*{box-sizing:border-box}body{margin:0 auto;color:#333}
/*# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9iYXNlLnNjc3MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsRUFDSSxxQkFBc0IsQ0FFMUIsS0FDSSxhQUFjLENBQ2QsVUFBVyIsImZpbGUiOiJhcHAuY3NzIiwic291cmNlc0NvbnRlbnQiOlsiKiB7XHJcbiAgICBib3gtc2l6aW5nOiBib3JkZXItYm94O1xyXG59XHJcbmJvZHkge1xyXG4gICAgbWFyZ2luOiAwIGF1dG87XHJcbiAgICBjb2xvcjogIzMzMztcclxufSJdfQ== */

Yeah, it’s meant to do that.

If you don’t pass an argument to sourcemaps.write(), the plugin will embed them in the source file.

To write external source map files, pass a path relative to the destination to sourcemaps.write() .

E.g.:

.pipe(sourcemaps.write('../maps'))

You can read more here:

I’m also getting a lot of errors following this tutorial. When you suggest amendments can you ask the author to note the node and npm versions they are using. And, as a bonus it would be helpful to have the complete gulpfile.js attached at the end of the tutorial to make sure nothing is missed out.

Hi, I’ve passed your comments on to HQ, so they will hopefully make those ammendments soon.

In the meantime, what worked for me when helping @ Riadkilani was Node v12.16.1 (latest LTS) and npm v16.14.2.

Here is the gulpfile I ended up with:

const assets = require('postcss-assets');
const autoprefixer = require('autoprefixer');
const concat = require('gulp-concat');
const cssnano = require('cssnano');
const deporder = require('gulp-deporder');
const gulp = require('gulp');
const htmlclean = require('gulp-htmlclean');
const imagemin = require('gulp-imagemin');
const mqpacker = require('css-mqpacker');
const newer = require('gulp-newer');
const noop = require('gulp-noop');
const postcss = require('gulp-postcss');
const sass = require('gulp-sass');
const terser = require('gulp-terser');

// development mode?
// const devBuild = (process.env.NODE_ENV !== 'production');
const devBuild = false;

const stripdebug = devBuild ? null : require('gulp-strip-debug');
const sourcemaps = devBuild ? require('gulp-sourcemaps') : null;

// folders
const src = 'src/';
const build = 'build/';

// image processing
function images() {
  const out = `${build}images/`;
  return gulp.src(`${src}images/**/*`)
    .pipe(newer(out))
    .pipe(imagemin({ optimizationLevel: 5 }))
    .pipe(gulp.dest(out));
}

function html() {
  const out = `${build}html/`;
  return gulp.src(`${src}html/**/*`)
    .pipe(newer(out))
    .pipe(devBuild ? noop() : htmlclean())
    .pipe(gulp.dest(out));
}

function js() {
  return gulp.src(`${src}js/**/*`)
    .pipe(sourcemaps ? sourcemaps.init() : noop())
    .pipe(deporder())
    .pipe(concat('main.js'))
    .pipe(stripdebug ? stripdebug() : noop())
    .pipe(terser())
    .pipe(sourcemaps ? sourcemaps.write() : noop())
    .pipe(gulp.dest(`${build}js/`));
}

// CSS processing
function css() {
  return gulp.src(`${src}scss/main.scss`)
    .pipe(sourcemaps ? sourcemaps.init() : noop())
    .pipe(sass({
      outputStyle: 'nested',
      imagePath: '/images/',
      precision: 3,
      errLogToConsole: true,
    }).on('error', sass.logError))
    .pipe(postcss([
      assets({ loadPaths: ['images/'] }),
      autoprefixer({ browsers: ['last 2 versions', '> 2%'] }),
      mqpacker,
      cssnano,
    ]))
    .pipe(sourcemaps ? sourcemaps.write() : noop())
    .pipe(gulp.dest(`${build}css/`));
}

exports.css = gulp.series(images, css);
exports.js = js;
exports.images = images;
exports.html = gulp.series(images, html);

Please try that and let me know if there is anything in particular that isn’t working for you.

1 Like

That works, although it does throw errors for autoprefixer (already flagged above).

I’m confused with the goal of An Introduction to Gulp.js, I was expecting to step through adding browser-sync and creating a gulp watch command. My goal was to setup a gulp project where I could edit html, js, scss and see changes replicated in a live environment.

You can also do this with webpack. Webpack itself would take care of the SCSS > CSS transpilation, whereas webpack-dev-server would provide the live dev environment.

Here’s a a tutorial on setting up webpack.

I just followed it through to make sure I’m not recommending anything outdated (JavaScript changes waaay to quickly) and can confirm that it works as expected :slight_smile:

If you’re not too invested in Gulp, I would give that a go and see if it fits your needs.

And BTW, webpack also brings some further benefits to the table, such as allowing you to write your JavaScript using modules (which it will bundle) and the latest syntax (which it will transpile).

1 Like

Actually, thinking about it, this npm package may be better suited to your needs.

You’d still need some way of compiling SCSS to CSS, but you could do this with Webpack or with Gulp.

You would install live-server on your machine globally, then use it to serve your site. Simultaneously, you’d kick off your SCSS > CSS transpilation using a watch flag, so that it would recompile when you make any changes.

1 Like

I’ve used Gulp in the past with browser-sync. I wanted to upgrade to v4 and migrate some existing projects over.

To confirm, the desired outcome for someone following the An Introduction to Gulp.js tutorial is to create a gulp file, do some setup, then move onto webpack. Is there somewhere where I can provide feedback on this?

Not really. If you have an old Gulp project running successfully with Browser sync, then I would upgrade that. From what you posted above, it sounded like you were new to using Gulp. My replies were just how I would go about tackling the problem you outlined.

You can leave a review on the book page, or you can post here. I can make sure that any feedback gets passed on.