Gulp doesn't notice my file changes - node.js

I'm working on a project with a few others. While they get Gulp to work, it doesn't seem to work on my computer, even through our code is identical.
When I write the 'gulp' command, I get this:
[10:51:17] Starting 'browserify'...
[10:51:19] Finished 'browserify' after 2.37 s
[10:51:19] Starting 'default'...
[10:51:19] Finished 'default' after 17 μs
But when I save the changes in the files Gulp is suppose to be watching, the 'update' event doesnt seem to be triggered.
Here is the Gulp file
var gulp = require("gulp"),
jest = require("gulp-jest"),
source = require('vinyl-source-stream'),
browserify = require('browserify'),
watchify = require('watchify'),
reactify = require('reactify');
require("harmonize")();
var paths = {
scripts: "src/**/*.js",
tests: "__tests__"
};
gulp.task("jest", function () {
return gulp.src(paths.tests).pipe(jest({
scriptPreprocessor: "preprocessor.js",
unmockedModulePathPatterns: [
"../node_modules/react"
],
testPathIgnorePatterns: [
"node_modules",
"spec/support"
],
moduleFileExtensions: [
"js",
"json",
"react"
]
}));
});
gulp.task('browserify', function() {
var bundler = browserify({
entries: ['./src/js/TopLevel.js'],
transform: [reactify],
debug: true,
cache: {}, packageCache: {}, fullPaths: true
});
var watcher = watchify(bundler);
return watcher
.on('update', function () { // When any files update
var updateStart = Date.now();
console.log('Updating!');
watcher.bundle() // Create new bundle that uses the cache for high performance
.pipe(source('main.js'))
.pipe(gulp.dest('./public/assets/js'));
console.log('Updated!', (Date.now() - updateStart) + 'ms');
})
.bundle() // Create the initial bundle when starting the task
.pipe(source('main.js'))
.pipe(gulp.dest('./public/assets/js'));
});
gulp.task("watch", function() {
gulp.watch("src/**/*.js", ["jest"]);
gulp.watch("__tests__/*.js", ["jest"]);
});
gulp.task("default", ["browserify"]);
However, I don't think there is anything wrong with the code, as it works for my other team members.
Any help and comments are highly appreciated!

Try this:
gulp.task("watch", function() {
gulp.watch("./src/**/*.js", ["jest"]);
gulp.watch("./__tests__/*.js", ["jest"]);
});

If you are only running gulp in the command line the watch task will not trigger since the default task is only running browserify, just change your default task to this.
gulp.task("default", ["browserify", "watch"]);

Related

Gulp project running locally but unable to build

I am trying building a website with a clone from https://github.com/cssninjaStudio/krypton.
I can run the project locally with yarn run dev command working properly, but when i try to build the app to host in a VPS with yarn build or yarn run prod giving an error
Task never defined: prod
Here is my gulp.js
const del = require('del');
const options = require("./config");
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
const bourbon = require('node-bourbon').includePaths;
const postcss = require('gulp-postcss');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const imagemin = require('gulp-imagemin');
const cleanCSS = require('gulp-clean-css');
const purgecss = require('gulp-purgecss');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const panini = require('panini');
const browserify = require("browserify");
const babelify = require("babelify");
const source = require("vinyl-source-stream");
const nodepath = 'node_modules/';
sass.compiler = require('sass');
//Note : Webp still not supported in major browsers including forefox
//const webp = require('gulp-webp'); //For converting images to WebP format
//const replace = require('gulp-replace'); //For Replacing img formats to webp in html
const logSymbols = require('log-symbols'); //For Symbolic Console logs :) :P
//Load Previews on Browser on dev
function livePreview(done) {
browserSync.init({
server: {
baseDir: options.paths.dist.base
},
port: options.config.port || 5000
});
done();
}
//Copy latest installed Bulma
function setupBulma() {
console.log("\n\t" + logSymbols.info, "Installing Bulma Files..\n");
return src([nodepath + 'bulma/*.sass', nodepath + 'bulma/**/*.sass'])
.pipe(dest('src/sass/'));
}
//Compile Sass code
function compileSASS() {
console.log("\n\t" + logSymbols.info, "Compiling Bulma Sass..\n");
return src(['src/sass/bulma.sass'])
.pipe(sass({
outputStyle: 'compressed',
sourceComments: 'map',
sourceMap: 'sass',
includePaths: bourbon
}).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(dest('dist/assets/css'))
.pipe(browserSync.stream());
}
//Compile Scss code
function compileSCSS() {
console.log("\n\t" + logSymbols.info, "Compiling App SCSS..\n");
return src(['src/scss/main.scss'])
.pipe(sass({
outputStyle: 'compressed',
sourceComments: 'map',
sourceMap: 'scss',
includePaths: bourbon
}).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(dest('dist/css'))
.pipe(browserSync.stream());
}
//Compile HTML partials with Panini
function compileHTML() {
console.log("\n\t" + logSymbols.info, "Compiling HTML..\n");
panini.refresh();
return src('src/pages/**/*.html')
.pipe(panini({
root: 'src/pages/',
layouts: 'src/layouts/',
partials: 'src/partials/',
helpers: 'src/helpers/',
data: 'src/data/'
}))
.pipe(dest('dist'))
.pipe(browserSync.stream());
}
//Concat CSS Plugins
function concatCssPlugins() {
console.log("\n\t" + logSymbols.info, "Compiling Plugin styles..\n");
return src([
nodepath + 'simplebar/dist/simplebar.min.css',
nodepath + 'plyr/dist/plyr.css',
nodepath + 'codemirror/lib/codemirror.css',
nodepath + 'codemirror/theme/shadowfox.css',
'src/vendor/css/*',
])
.pipe(sourcemaps.init())
.pipe(concat('app.css'))
.pipe(sourcemaps.write('./'))
.pipe(dest('dist/css'))
.pipe(browserSync.stream());
}
//Reset Panini Cache
function resetPages(done) {
console.log("\n\t" + logSymbols.info, "Clearing Panini Cache..\n");
panini.refresh();
done();
}
//Triggers Browser reload
function previewReload(done) {
console.log("\n\t" + logSymbols.info, "Reloading Browser Preview.\n");
browserSync.reload();
done();
}
//Development Tasks
function devHTML() {
return src(`${options.paths.src.base}/**/*.html`).pipe(dest(options.paths.dist.base));
}
//Optimize images
function devImages() {
return src(`${options.paths.src.img}/**/*`).pipe(dest(options.paths.dist.img));
}
// Let's write our task in a function to keep things clean
function javascriptBuild() {
// Start by calling browserify with our entry pointing to our main javascript file
return (
browserify({
entries: [`${options.paths.src.js}/main.js`],
// Pass babelify as a transform and set its preset to #babel/preset-env
transform: [babelify.configure({ presets: ["#babel/preset-env"] })]
})
// Bundle it all up!
.bundle()
// Source the bundle
.pipe(source("bundle.js"))
// Then write the resulting files to a folder
.pipe(dest(`dist/js`))
);
}
function copyFonts() {
console.log("\n\t" + logSymbols.info, "Copying fonts to dist folder.\n");
return src([
'src/fonts/*',
])
.pipe(dest('dist/fonts'))
.pipe(browserSync.stream());
}
//Copy data files
function copyData() {
console.log("\n\t" + logSymbols.info, "Copying data files..\n");
return src([
'src/data/**/*',
])
.pipe(dest('dist/data'))
.pipe(browserSync.stream());
}
function watchFiles() {
//watch('src/**/*.html', compileHTML);
watch(`${options.paths.src.base}/**/*.html`, series(compileHTML, previewReload));
watch(['src/scss/**/*', 'src/scss/*'], compileSCSS);
watch(`${options.paths.src.js}/**/*.js`, series(javascriptBuild, previewReload));
watch(`${options.paths.src.img}/**/*`, series(devImages, previewReload));
console.log("\n\t" + logSymbols.info, "Watching for Changes..\n");
}
function devClean() {
console.log("\n\t" + logSymbols.info, "Cleaning dist folder for fresh start.\n");
return del([options.paths.dist.base]);
}
exports.setup = series(setupBulma);
exports.default = series(
devClean, // Clean Dist Folder
resetPages,
parallel(copyFonts, concatCssPlugins, compileSCSS, javascriptBuild, devImages, compileHTML),
livePreview, // Live Preview Build
watchFiles // Watch for Live Changes
);
Need some help to build this website and host it in VPS
Many Thanks in Advance
The prod task is not define within the Gulp file. The dev task is, because it is calling the default gulp task (gulp with no arg is calling the default which is found at the end of the gulp file
exports.default = series(
devClean, // Clean Dist Folder
resetPages,
parallel(copyFonts, concatCssPlugins, compileSCSS, javascriptBuild, devImages, compileHTML),
livePreview, // Live Preview Build
watchFiles // Watch for Live Changes
);
Take a look at your package.json file, this is were the script name are define (such as dev and prod.)
"scripts": {
"dev": "gulp",
"build": "gulp prod",
"prod": "gulp prod",
"preinstall": "npx npm-force-resolutions"
},
So you should create a prod method in your gulp.js and should only call usefull method for prod env (remove livePreview and watch, you are most likely only build and deploy.)
I prefer to task definition like this,
gulp.task("prod", function (callback) {
config.runCleanBuilds = true;
return runSequence(
"taskA",
"taskB",
"taskC",
callback);
});
but you could do it the same way they do in their gulp file I guess
exports.prod = series(
devClean, // Clean Dist Folder
resetPages,
parallel(copyFonts, concatCssPlugins, compileSCSS, javascriptBuild, devImages, compileHTML)
);

Gulp 4 error: "Did you forget to signal async completion?"

I am working on a small project that needs .sass files compiled into .css files. I have used Gulp a while ago and loved it, but my old gulpfile.js does not work anymore, because Gulp has changed since version 4.
I have made a new gulpfile.js:
var gulp = require('gulp'),
sass = require('gulp-sass'),
rename = require('gulp-rename');
var paths = {
styles: {
src: 'src/scss/*.scss',
dest: 'build/css'
}
};
function styles() {
return gulp
.src(paths.styles.src, {
sourcemaps: true
})
.pipe(sass())
.pipe(rename({
basename: 'main',
suffix: '.min'
}))
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp
.watch(paths.styles.src, styles);
}
var syncConfig = {
server: {
baseDir : './',
index : 'index.html'
},
port : 3000,
open : false
};
// browser-sync
function server() {
init(syncConfig);
}
var build = gulp.parallel(styles, watch, server);
gulp
.task(build);
gulp
.task('default', build);
I have a "Did you forget to signal async completion?" error returned by the console.
Where is my mistake?
There ware two things missing: the browsersync variable browsersync = require('browser-sync').create() and the callback for the server function:
function server(done) {
if (browsersync) browsersync.init(syncConfig);
done();
}
It compiles SASS to CSS, still there is this problem: the page does not reload automatically when changes are made in the main.scss.
Here is the entire code:
var gulp = require('gulp'),
browsersync = require('browser-sync').create(),
sass = require('gulp-sass'),
rename = require('gulp-rename');
var paths = {
styles: {
src: 'src/scss/*.scss',
dest: 'build/css'
}
};
function styles() {
return gulp
.src(paths.styles.src, {
sourcemaps: true
})
.pipe(sass())
.pipe(rename({
basename: 'main',
suffix: '.min'
}))
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp
.watch(paths.styles.src, styles);
}
var syncConfig = {
server: {
baseDir : './',
index : 'index.html'
},
port : 3000,
open : false
};
// browser-sync
function server(done) {
if (browsersync) browsersync.init(syncConfig);
done();
}
var build = gulp.parallel(styles, watch, server);
gulp
.task(build);
gulp
.task('default', build);

Different builds based on targeting client vs server code

I currently have 2 separate webpack builds for server rendered vs client rendered code. Is there an easy way to change the build output based on server/client build?
For example something like this:
// Have some code like this
if(is_client){
console.log('x.y.z')
} else {
server.log('x.y.z')
}
// Webpack outputs:
// replaced code in client.js
console.log('x.y.z')
// replaced code in server.js
server.log('x.y.z')
Have you tried anything like this?
// webpack.config.js
module.exports = () => ['web', 'node'].map(target => {
const config = {
target,
context: path.resolve('__dirname', 'src'),
entry: {
[target]: ['./application.js'],
},
output: {
path: path.resolve(__dirname, 'dist', target),
filename: '[name].js'
},
modules: { rules: ... },
plugins: [
new webpack.DefinePlugin({
IS_NODE: JSON.stringify(target === 'node'),
IS_WEB: JSON.stringify(target === 'web'),
}),
],
};
return config;
});
// later in your code
import logger from 'logger';
if (IS_NODE) {
logger.log('this is node js');
}
if (IS_WEB) {
console.log('this is web');
}
how the compilation works?
// client.bundle.js
import logger from 'logger';
// DefinePlugin creates a constant expression which causes the code below to be unreachable
if (false) {
logger.log('this is node js');
}
if (true) {
console.log('this is web');
}
Finally you will produce your build in production mode, so webpack will include a plugin called UglifyJS, this has a feature called dead code removal (aka tree shaking), so it will delete any unused/unreachable code.
and the final result will look like:
// node.bundle.js
import logger from 'logger';
console.log('this is node js');
//web.bundle.js
console.log('this is node js');

gulp build with browser sync and react not reloading page

I have a gulpfile with the following build task:
var gulp = require('gulp'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
babelify = require('babelify'),
browserify = require('browserify'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
bs = require('browser-sync').create('BrowserSync');
gulp.task('build', function () {
return browserify({entries: './src/app.js', debug: true})
.transform("babelify", { presets: ['es2015','react'] })
.bundle()
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./dist/js'))
.pipe(bs.reload({stream: true}));
});
The process builds my files perfectly, however my browser does not load. Why doesn't my browser reload? And how do I achieve the desired behavior? I feel like I am missing something about BrowserSync.
NOTE: I am fairly confident BrowserSync is working properly as I call bs.reload() in another task, and the page reloads perfectly. Happy to paste in more code however if needed.
Here is a snippet from a starter project that I started a while back that does what you are mentioning...
/*...*/
gulp.task('watchify', () => {
let args = merge(watchify.args, { debug: true })
let bundler = watchify(browserify('./src/js/app.js', args)).transform(babelify, { presets: ["es2015", "react"] })
bundle(bundler)
bundler.on('update', () => {
bundle(bundler)
})
})
function bundle(bundler) {
return bundler.bundle()
.on('error', map_error)
.pipe(source('app.js'))
.pipe(buffer())
.pipe(rename('app.min.js'))
.pipe(sourcemaps.init({ loadMaps: true }))
// capture sourcemaps from transforms
.pipe(uglify())
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./dist/js'))
.pipe(sync.reload({
stream: true
}))
}
/*...*/
// watching multiple files with a task 'watch'
gulp.task('default', () => {
gulp.watch('src/js/**/*.js', ['watchify']);
});
The gulp task that started browsersync was run by gulp as it was triggered in the default task.
Then I ran gulp build manually from the terminal, and here was the issue. This manual command thus did not have access to the instance of browsersync that was created by the default gulp process.
So having gulp build run automatically with the instantiated version available did the trick.

requirejs optimization with gulp

I am using requirejs and gulp to build angular app. I am using amd-optimize and gulp-requirejs-optimize to add all js files into single file. Here is my main.js file:
require.config(
{
paths: {
app : 'app',
angular : '../bower_components/angular/angular',
jquery : '../bower_components/jquery/dist/jquery',
angularResource : '../bower_components/angular-resource/angular-resource',
angularRoute : '../bower_components/angular-route/angular-route',
publicModule : 'public_module',
route : 'route'
},
shim: {
'app': {
deps: ['angular']
},
'angularRoute': ['angular'],
angular : {exports : 'angular'}
}
}
);
And gulpfile.js
var gulp = require('gulp');
var rjs = require('gulp-requirejs');
var connect = require('gulp-connect');
var requirejsOptimize = require('gulp-requirejs-optimize');
var amdOptimize = require('amd-optimize');
var concat = require('gulp-concat');
// using amd-optimize.
gulp.task('bundle', function () {
return gulp.src('app/**/*.js')
.pipe(amdOptimize('main'))
.pipe(concat('main-bundle.js'))
.pipe(gulp.dest('dist'));
});
// using gulp-requirejs-optimize.
gulp.task('scripts', function () {
return gulp.src('app/main.js')
.pipe(requirejsOptimize())
.pipe(gulp.dest('dist'));
});
When I run gulp bundle or gulp scripts, it shows me same content of main.js file in output file(not showing all js template in one output file).
The output file is:
require.config({
paths: {
angular: '../bower_components/angular/angular',
jquery: '../bower_components/jquery/dist/jquery',
angularResource: '../bower_components/angular-resource/angular-resource',
angularRoute: '../bower_components/angular-route/angular-route',
publicModule: 'public_module',
route: 'route'
},
shim: {
'app': { deps: ['angular'] },
'angularRoute': ['angular'],
angular: { exports: 'angular' }
}
});
define('main', [], function () {
return;
});
How can I configure gulp to put every js template into one js file?
check the docs for all the options for amdoptimize. For example you can point to your config file or add paths.
I always have trouble getting all the paths to line up, so make sure to check them diligently.
here is how you can start to put the options in:
gulp.task('requirejsBuild', function() {
gulp.src('app/**/*.js',{ base: 'app' })
.pipe(amdOptimize("app",{
baseUrl: config.app,
configFile: 'app/app-config.js',
findNestedDependencies: true,
}))
.pipe(concat('app.js'))
.pipe(gulp.dest('dist'))
});
You are not requiring any files - you just define an empty module named main.
You need to kick off you app by requiring a module, eg.
require(['app'], function (App) {
new App().init();
});

Resources