How to restart app using gulp when node modules updated? - javascript

I am using npm link to link other package here in this project now when that package got updated i want to use auto watch feature and restart the app.
How to watch changes for node modules ?
gulp.js
var gulp = require("gulp");
var ts = require("gulp-typescript");
var uglify = require("gulp-uglifyes");
var gulpif = require("gulp-if");
var log = require("fancy-log");
var nodemon = require('gulp-nodemon');
var tsProject = ts.createProject("tsconfig.json");
gulp.task("default", () => {
return tsProject.src().pipe(tsProject()).pipe(gulpif(arg.env === 'prod', uglify())).pipe(gulp.dest("dist"));
});
gulp.task('stream', ['default'], function develop() {
var stream = nodemon({
script: 'server.js',
ext: 'js',
watch: "../project/local",
ignore: ['ignored.js'],
tasks: ["default"]
}) return stream.on('restart', function() {
console.log('restarting nodemon')
}).on('crash', function() {
console.error('Application has crashed!\n') stream.emit('restart', 10)
})
})

Related

AssertionError while using gulp. 'Task function must be specified'

I'm trying to use Gulp as part of a React tutorial I'm walking through. After installing the dependencies I've been given;
AssertionError [ERR_ASSERTION]: Task function must be specified
This is the gulpfile.js which I am using
'use strict';
// dependencies
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var renamed = require('gulp-rename');
var changed = require('gulp-changed');
// - SCSS/CSS
var SCSS_SRC = './src/Assets/scss/**/*.scss';
var SCSS_DEST = './src/Assets/css';
// Compile SCSS
gulp.task('compile_scss', function(){
gulp.src(SCSS_SRC)
.pipe(sass().on('error', sass.logError))
.pipe(minifyCSS())
.pipe(rename({ suffix: '.min' }))
.pipe(changed(SCSS_DEST))
.pipe(gulp.dest(SCSS_DEST));
});
// detect changes in SCSS
gulp.task('watch_scss', function(){
gulp.watch(SCSS_SRC, ['compile_scss']);
});
// Run tasks
gulp.task('default', ['watch_scss']);
And this outputs the following messages
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
The tutorial I am using was made in April 2017. Could it be something to do with conflicting versions?
Any help is appreciated.
The problem was I was using v3 gulp, the problem was solved by upgrading to v4.
The code is below.
'use strict';
// dependencies
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var renamed = require('gulp-rename');
var changed = require('gulp-changed');
// - SCSS/CSS
var SCSS_SRC = './src/Assets/scss/**/*.scss';
var SCSS_DEST = './src/Assets/css';
function compile_scss (done) {
gulp.src(SCSS_SRC)
.pipe(sass().on('error', sass.logError))
.pipe(minifyCSS())
.pipe(renamed({ suffix: '.min' }))
.pipe(changed(SCSS_DEST))
.pipe(gulp.dest(SCSS_DEST));
done();
}
// detect changes in SCSS
function detect_change_scss (done) {
gulp.watch(SCSS_SRC)
done();
}
// Run tasks
gulp.task("compile_scss", gulp.series(compile_scss, detect_change_scss, ));

Does the debugger command get removed after a minify

I hate javascript tooling.
I have this config file:
var source = require('vinyl-source-stream');
var gulp = require('gulp');
var tap = require('gulp-tap');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var csso = require('gulp-csso');
var jshint = require('gulp-jshint');
var watchify = require('watchify');
var browserify = require('browserify');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
gulp.task('prod', ['assets', 'prod-css'], function() {
return browserify('./src/main.js', {
standalone: standalone
}).transform('babelify',
{ presets: ["#babel/preset-env"],
plugins: [] })
.bundle()
.on('error', onError)
.pipe(source('okeyground.min.js'))
.pipe(streamify(uglify()))
.pipe(gulp.dest(destination));
});
when I add a debugger; command it doesn't get produced in the minified js. Does it get removed, or how can I put it in.
In your code set the drop_debugger property to false in the compress options:
.pipe(
uglify({
compress: {
drop_debugger: false,
},
})
)

Add tsconfig.json properties to Gulp task

I keep on getting that error about using something different than ES5 standards while compiling, simply because I just started using TS and I don't know how to include the tsconfig.json directly in my Gulp task autocompile.
error TS1056: Accessors are only available when targeting ECMAScript 5 and higher
Is it possible to add my tsconfig.json file properties directly into my Gulp pipe?
Current gulpfile.js
'use strict';
var gulp = require('gulp');
var ts = require('gulp-typescript');
var tsProject = ts.createProject('tsconfig.json'); // TypeScript config
var merge = require('merge2'); // TypeScript requirement
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
gulp.task('sass', function () {
return gulp.src('app/assets/scss/**/*.scss')
.pipe(sass()) // Using gulp-sass
.pipe(gulp.dest('app/assets/css'))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('typescript', function () {
var tsResult = gulp.src('app/assets/typescript/**/*.ts')
.pipe(ts({
declaration: true
}));
return merge([
tsResult.dts.pipe(gulp.dest('app/assets/definitions')),
tsResult.js.pipe(gulp.dest('app/assets/js'))
]);
});
gulp.task('watch', ['browserSync', 'sass'], function () {
gulp.watch('app/assets/typescript/**/*.ts', ['typescript']);
gulp.watch('app/assets/scss/**/*.scss', ['sass']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('app/**/*.html', browserSync.reload);
gulp.watch('app/assets/js/**/*.js', browserSync.reload);
});
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: 'app'
},
});
});
gulp.task('useref', function () {
return gulp.src('app/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
// Minifies only if it's a CSS file
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('app/assets/img/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest('dist/assets/img'));
});
gulp.task('fonts', function () {
return gulp.src('app/assets/fonts/**/*')
.pipe(gulp.dest('dist/assets/fonts'));
});
gulp.task('clean:dist', function () {
return del.sync('dist');
});
gulp.task('build', function (callback) {
runSequence('clean:dist', ['sass', 'useref', 'images', 'fonts'],
callback
);
});
gulp.task('default', function (callback) {
runSequence(['sass', 'typescript', 'browserSync', 'watch'],
callback
);
// Typescript compiler
});
I would recommend you to use your tsconfig.json as the only source of the properties. To do this change how you create tsResult:
var tsProject = ts.createProject('tsconfig.json');
var tsResult = tsProject.src().
.pipe(//....
Below is the complete task that works for me:
gulp.task('build.js.dev', () =>
{
var tsProject = ts.createProject('tsconfig.json');
var tsResult = tsProject.src()
.pipe(sourcemaps.init())
.pipe(tsProject());
return merge([
//Write definitions
//tsResult.dts.pipe(gulp.dest(TEMP_TARGET_FOLDER)),
//Write compiled js
tsResult.js.pipe(sourcemaps.write(
".",
{
includeContent: true,
sourceRoot: __dirname + "/dist"
})).pipe(gulp.dest(TEMP_TARGET_FOLDER))]);
});
The error you are getting is due to the fact that if you omit target compiler option the typescript compiler will fallback to ES3.

Gulp - output files not created

Below is a gulp task that has been created to compile angular2 tests written in typescript.
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var debug = require('gulp-debug');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var typescript = require('typescript');
var tsTestProject = $.typescript.createProject({
target: 'es5',
sortOutput: true,
typescript: typescript,
experimentalDecorators: true
});
gulp.task('scripts-test', [], function () {
var gulpStream = gulp.src([
path.join(conf.paths.src, '/app/references.test.ts'),
path.join(conf.paths.src, '/app/**/*.spec.ts')
])
.pipe(debug())
.pipe($.sourcemaps.init())
.pipe($.typescript(tsTestProject)).on('error', conf.errorHandler('TypeScript'))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('tmptest'))
.pipe(browserSync.reload({ stream: true }))
.pipe($.size());
return gulpStream;
});
Here's the log related to the task.
[20:47:45] Starting 'scripts-test'...
[20:50:18] TypeScript: emit succeeded (with errors)
[20:50:18] Finished 'scripts-test' after 2.53 min
Yet no output files (typescripts compiled into js) are created to a tmptest folder as given in the task. gulp-debug shows that all the files given in gulp.src are acquired to the stream. Any idea as to why this is happening?

gulp browserify reactify task is quite slow

I am using Gulp as my task runner and browserify to bundle my CommonJs modules.
I have noticed that running my browserify task is quite slow, it takes around 2 - 3 seconds, and all I have is React and a few very small components I have built for development.
Is there a way to speed up the task, or do I have any noticeable problems in my task?
gulp.task('browserify', function() {
var bundler = browserify({
entries: ['./main.js'], // Only need initial file
transform: [reactify], // Convert JSX to javascript
debug: true, cache: {}, packageCache: {}, fullPaths: true
});
var watcher = watchify(bundler);
return watcher
.on('update', function () { // On update When any files updates
var updateStart = Date.now();
watcher.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./'));
console.log('Updated ', (Date.now() - updateStart) + 'ms');
})
.bundle() // Create initial bundle when starting the task
.pipe(source('bundle.js'))
.pipe(gulp.dest('./'));
});
I am using Browserify, Watchify, Reactify and Vinyl Source Stream as well as a few other unrelated modules.
var browserify = require('browserify'),
watchify = require('watchify'),
reactify = require('reactify'),
source = require('vinyl-source-stream');
Thanks
See fast browserify builds with watchify. Note that the only thing passed to browserify is the main entry point, and watchify's config.
The transforms are added to the watchify wrapper.
code from article pasted verbatim
var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var browserify = require('browserify');
var bundler = watchify(browserify('./src/index.js', watchify.args));
// add any other browserify options or transforms here
bundler.transform('brfs');
gulp.task('js', bundle); // so you can run `gulp js` to build the file
bundler.on('update', bundle); // on any dep update, runs the bundler
function bundle() {
return bundler.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('bundle.js'))
// optional, remove if you dont want sourcemaps
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
.pipe(sourcemaps.write('./')) // writes .map file
//
.pipe(gulp.dest('./dist'));
}
You have to use watchify and enable its cache. Take a look at :
https://www.codementor.io/reactjs/tutorial/react-js-browserify-workflow-part-2
and for more optimisation when building source-map you could do that :
cd node_modules/browserify && npm i substack/browser-pack#sm-fast
this would safe you half of time
part of my gulpfile.js
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var htmlreplace = require('gulp-html-replace');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify = require('watchify');
var reactify = require('reactify');
var streamify = require('gulp-streamify');
var path = {
OUT : 'build.js',
DEST2 : '/home/apache/www-modules/admimail/se/se',
DEST_BUILD : 'build',
DEST_DEV : 'dev',
ENTRY_POINT : './src/js/main.jsx'
};
gulp.task('watch', [], function() {
var bundler = browserify({
entries : [ path.ENTRY_POINT ],
extensions : [ ".js", ".jsx" ],
transform : [ 'reactify' ],
debug : true,
fullPaths : true,
cache : {}, // <---- here is important things for optimization
packageCache : {} // <---- and here
});
bundler.plugin(watchify, {
// delay: 100,
// ignoreWatch: ['**/node_modules/**'],
// poll: false
});
var rebundle = function() {
var startDate = new Date();
console.log('Update start at ' + startDate.toLocaleString());
return bundler.bundle(function(err, buf){
if (err){
console.log(err.toString());
} else {
console.log(' updated in '+(new Date().getTime() - startDate.getTime())+' ms');
}
})
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST2 + '/' + path.DEST_DEV))
;
};
bundler.on('update', rebundle);
return rebundle();
});
gulp.task('default', [ 'watch' ]);
Many thanks to #PHaroZ for that answer. I had to modify a little bit that code for my needs though. I am working with ReactJS on Symfony2 framework and all my builds were taking 7s-21s!!! Crazy.. So that's what I have now:
var path = {
OUT : 'app.js',
DEST_BUILD : './src/MyBundle/Resources/js/dist',
ENTRY_POINT : './src/MyBundle/Resources/js/src/app.js'
};
gulp.task('watch', [], function() {
var bundler = browserify({
entries : [ path.ENTRY_POINT ],
extensions : [ ".js", ".jsx" ],
// transform : [ 'reactify' ],
debug : true,
fullPaths : true,
cache : {}, // <---- here is important things for optimization
packageCache : {} // <---- and here
}).transform("babelify", {presets: ["es2015", "react"]});
bundler.plugin(watchify, {
// delay: 100,
// ignoreWatch: ['**/node_modules/**'],
// poll: false
});
var rebundle = function() {
var startDate = new Date();
console.log('Update start at ' + startDate.toLocaleString());
return bundler.bundle(function(err, buf){
if (err){
console.log(err.toString());
} else {
console.log(' updated in '+(new Date().getTime() - startDate.getTime())+' ms');
}
})
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST_BUILD))
;
};
bundler.on('update', rebundle);
return rebundle();
});
Now first compile takes around 20s and each time I update my file it takes around 800ms. It's just enough time to switch from IDE to my browser.

Categories

Resources