I am pretty new to gulp and browserify. I have written a gulpfile.js like this.
gulp.task('default', function (done) {
var b = browserify({
entries: ['app/app.js'],
});
var browserifiedCode = b
.transform(bulkify)
.bundle()
.on('error', function(err) {
gutil.log('Browserify Error', gutil.colors.red(err));
gutil.beep();
this.emit('end');
})
.pipe(source('app.browserified.js')) --> what does it mean ??
.pipe(buffer());
var nonBrowserifyLibraries = [];
var output = gulpMerge(
gulp.src(nonBrowserifyLibraries),
browserifiedCode
)
.pipe(concat('app.js'));
//output = output.pipe(uglify());
return output.pipe(gulp.dest('./'));
After running gulp it is creating app.js but when I am running it in browser then I am getting error Uncaught TypeError: fs.readdirSync is not a function
Can any one help me out.
Thanks
EDITED : I am using bulk-require which somewhere has fs.readdirSync(abc) , I am sure it is creating a problem.
Even without gulp when I did browserify app/app.js -o app.js and loaded this app.js in browser still I got the same fs.readdirSync error.
Try the following snippet, specific for only browserify task.
gulp.task('browserify', function () {
return browserify('app/app.js') // main source file
.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest('dist/app.js')); // destination file
});
Related
I know that this can be a very stupid question, but I can't find matches with other posts on stackoverflow...
So: Can I modify a file of an external module , just save the file and do something that my app can listen?
At the moment, i'm trying ti change some scss style at the ng2-datepicker module (inside node_modules folder), but if I save and the launch ng serve, changes will not affect my project.
I know it's a simple problem, but i don't know the background architecture of an Angular2 project.
Thanks in advance.
(ps I've seen that i can fork the git and then do something like npm install.
Very interesting, but i also want to know how to have the same result in local)
If you are using gulp file you can tell the changed lib file path to copy to build folder check gulp.task('copy-libs') in code below git repo for angular2-tour-of-heroes using gulp
const gulp = require('gulp');
const del = require('del');
const typescript = require('gulp-typescript');
const tscConfig = require('./tsconfig.json');
const sourcemaps = require('gulp-sourcemaps');
const tslint = require('gulp-tslint');
const browserSync = require('browser-sync');
const reload = browserSync.reload;
const tsconfig = require('tsconfig-glob');
// clean the contents of the distribution directory
gulp.task('clean', function () {
return del('dist/**/*');
});
// copy static assets - i.e. non TypeScript compiled source
gulp.task('copy:assets', ['clean'], function() {
return gulp.src(['app/**/*', 'index.html', 'styles.css', '!app/**/*.ts'], { base : './' })
.pipe(gulp.dest('dist'))
});
// copy dependencies
gulp.task('copy:libs', ['clean'], function() {
return gulp.src([
'node_modules/angular2/bundles/angular2-polyfills.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/rxjs/bundles/Rx.js',
'node_modules/angular2/bundles/angular2.dev.js',
'node_modules/angular2/bundles/router.dev.js',
'node_modules/node-uuid/uuid.js',
'node_modules/immutable/dist/immutable.js'
'yourpath/changedFileName.js'
])
.pipe(gulp.dest('dist/lib'))
});
// linting
gulp.task('tslint', function() {
return gulp.src('app/**/*.ts')
.pipe(tslint())
.pipe(tslint.report('verbose'));
});
// TypeScript compile
gulp.task('compile', ['clean'], function () {
return gulp
.src(tscConfig.files)
.pipe(sourcemaps.init())
.pipe(typescript(tscConfig.compilerOptions))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/app'));
});
// update the tsconfig files based on the glob pattern
gulp.task('tsconfig-glob', function () {
return tsconfig({
configPath: '.',
indent: 2
});
});
// Run browsersync for development
gulp.task('serve', ['build'], function() {
browserSync({
server: {
baseDir: 'dist'
}
});
gulp.watch(['app/**/*', 'index.html', 'styles.css'], ['buildAndReload']);
});
gulp.task('build', ['tslint', 'compile', 'copy:libs', 'copy:assets']);
gulp.task('buildAndReload', ['build'], reload);
gulp.task('default', ['build']);
I am trying to minify my script files for which i am using gulp task runner
And I am trying gulp-uglify plugin
Code:
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
// .pipe(concat('script.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist/'))
});
but i am getting error as
when i try to run gulp task as gulp concat
Any help would be appreciated
The main error is generated when you're using ES6 format. Use the gulp-uglify-es module instead of 'gulp-uglify' to overcome this error.
var uglify = require('gulp-uglify-es').default;
Note: gulp-uglify-es is no longer being maintained. You may want to use terser/gulp-terser instead:
To see the error in console:
var gutil = require('gulp-util');
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
// .pipe(concat('script.js'))
.pipe(uglify())
.on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); })
.pipe(gulp.dest('./dist/'))
});
To find the exact file, with line number of error register and run this task:
var pump = require('pump');
gulp.task('uglify-error-debugging', function (cb) {
pump([
gulp.src('app/**/*.js'),
uglify(),
gulp.dest('./dist/')
], cb);
});
I think the top answers here are not explaining how to get the error. The docs have a section on error handling:
gulp-uglify emits an 'error' event if it is unable to minify a
specific file
So, just capture the error and do whatever you want with it (such as logging to console) to see the filename, line number, and additional info:
uglify().on('error', console.error)
or in a larger context:
gulp.task('foo', () => {
return gulp.src([
'asset/src/js/foo/*.js',
'asset/src/js/bar/*.js',
])
.pipe(uglify().on('error', console.error))
.pipe(concat('bundle.js'))
.pipe(gulp.dest('./'));
});
This gives you a super helpful error!
{ GulpUglifyError: unable to minify JavaScript
at [stack trace])
cause:
{ SyntaxError: Continue not inside a loop or switch
[stack trace]
message: 'Continue not inside a loop or switch',
filename: 'ProductForm.js',
line: 301,
col: 37,
pos: 10331 },
plugin: 'gulp-uglify',
fileName:
'/asset/src/js/foo/ProductForm.js',
showStack: false }
Have you used ES6 format in your script file?
If so try ES5 now because when you do gulp-uglify it doesnt understand ES6 format as of now
and after that try your code
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
.pipe(concat('script.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist/'))
});
and run the task gulp concat it will work
For me, it was a deprecated option "preserveComments" that generated the error (and completely crashed the script).
Found the issue using:
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
.pipe(uglify())
.on('error', function (err) { console.log( err ) })
.pipe(gulp.dest('./dist/'))
});
Try using this
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var minifyJS = require('gulp-minify');
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
.pipe(minifyJS())
.pipe(concat('bundle.min.js'))
.pipe(uglify({ mangle: false }))
.pipe(gulp.dest('./dist/'));
});
you may have syntax error or used ES6 syntax. you can try https://skalman.github.io/UglifyJS-online/ firstly.
The main error to Unable to minifies JavaScript is the path not found. You can use the task usemin For this you need:
$ sudo npm install gulp-usemin --save-dev
$ sudo npm install gulp-livereload --save-dev
$ sudo npm install gulp-util --save-dev
and requires :
var usemin = require('gulp-usemin');
var livereload = require('gulp-livereload');
var gutil = require('gulp-util'); //gutil for error display
gulp.task('usemin',['jshint'], function(){
return gulp.src('./app/index.html')
.pipe(usemin({
css: [minifycss(),rev()],
scripts: [uglify().on('error', function(err) {gutil.log(gutil.colors.red('[Error]'), err.toString());this.emit('end');}),rev()]
}))
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
Change the js: [uglify(), rev()] to scripts: [uglify(), rev()]
I don't know if I missed something or made a mistake. But requiring a module only returns an empty object.
This is just a sample of my project.
Tools I'm using:
gulp - 3.9.1
browserify - 13.0.0
vinyl-source-stream - 1.1.0
Here is my working directory:
root/
dist/
src/
external.js
main.js
gulpfile.js
main.js
var External = require('./external.js');
console.log(External);
external.js
function Hello() {
return 'Hello from the otherside!';
}
module.exports = {
testFunc: Hello
};
gulpfile.js
var browserify = require('browserify');
var vinyl_source_stream = require('vinyl-source-stream');
gulp.task('concat', function() {
return browserify('./src/main.js')
.bundle()
.pipe(vinyl_source_stream('bundle.js'))
.pipe(gulp.dest('./dist/'))
});
First:
module.exports = function() {
testFunc: Hello
};
so that you can export an object prototype.
Second
var External = require('./external.js')(); // Notice the ()
so that you can execute that prototype and get an instance of the object.
Running into a bizarre bug when trying to make modular gulp tasks by splitting them into separate files. The following should execute the task css, but does not:
File: watch.js
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('watch', function () {
plugins.watch('assets/styl/**/*.styl', ['css']); // PROBLEM
});
Declaring ['css'] in plugins.watch() should technically run the following task next:
File: css.js
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('css', function () {
return gulp.src('assets/styl/*.styl')
.pipe(plugins.stylus())
.pipe(gulp.dest('/assets/css'));
});
File: gulpfile.js
var gulp = require('gulp');
var requireDir = require('require-dir');
requireDir('./gulp/tasks', { recurse: true });
gulp.task('develop', ['css', 'watch']);
Folder structure
- gulp/
- tasks/
- css.js
- watch.js
- gulpfile.js
Expected behavior
gulp develop should run tasks css and watch (it does). On file changes, watch should detect them (it does) and then run the css task (it's does not).
One solution
Not terribly fond of this solution as gulp.start() is being deprecated in the next release, but this does fix it:
File: watch.js
plugins.watch('assets/styl/**/*.styl', function() {
gulp.start('css');
});
Either use gulp's builtin watch with this syntax:
gulp.task('watch', function () {
gulp.watch('assets/styl/**/*.styl', ['css']);
});
Or gulp-watch plugin with this syntax:
gulp.task('watch', function () {
plugins.watch('assets/styl/**/*.styl', function (files, cb) {
gulp.start('css', cb);
});
});
There's also probably a typo in your gulp.dest path. Change it to relative:
.pipe(gulp.dest('assets/css'));
I am using Gulp 4, where gulp.start() is deprecated
So here's the solution
gulp.task('watch', gulp.series('some-task-name', function () {
browserSync.init({
server: {
baseDir: config.distFolder + ''
}
});
var watcher = gulp.watch([
'./src/views/*.html',
'./src/index.html',
'./src/assets/css/*.css',
'./src/**/*.js'],
gulp.series('some-task-name'));
watcher.on('change', async function (path, stats) {
console.log('you changed the code');
browserSync.notify("Compiling, please wait!");
browserSync.reload();
})
}));
Now, whenever there is a change in my code, my "some-task-name" gets executed and then the browser page is reloaded. I don't need to delay my browser-sync at all.
I have a set of gulp.js targets for running my mocha tests that work like a charm running through gulp-mocha. Question: how do I debug my mocha tests running through gulp? I would like to use something like node-inspector to set break points in my src and test files to see what's going on. I am already able to accomplish this by calling node directly:
node --debug-brk node_modules/gulp/bin/gulp.js test
But I'd prefer a gulp target that wraps this for me, e.g.:
gulp.task('test-debug', 'Run unit tests in debug mode', function (cb) {
// todo?
});
Ideas? I want to avoid a bash script or some other separate file since I'm trying to create a reusable gulpfile with targets that are usable by someone who doesn't know gulp.
Here is my current gulpfile.js
// gulpfile.js
var gulp = require('gulp'),
mocha = require('gulp-mocha'),
gutil = require('gulp-util'),
help = require('gulp-help');
help(gulp); // add help messages to targets
var exitCode = 0;
// kill process on failure
process.on('exit', function () {
process.nextTick(function () {
var msg = "gulp '" + gulp.seq + "' failed";
console.log(gutil.colors.red(msg));
process.exit(exitCode);
});
});
function testErrorHandler(err) {
gutil.beep();
gutil.log(err.message);
exitCode = 1;
}
gulp.task('test', 'Run unit tests and exit on failure', function () {
return gulp.src('./lib/*/test/**/*.js')
.pipe(mocha({
reporter: 'dot'
}))
.on('error', function (err) {
testErrorHandler(err);
process.emit('exit');
});
});
gulp.task('test-watch', 'Run unit tests', function (cb) {
return gulp.src('./lib/*/test/**/*.js')
.pipe(mocha({
reporter: 'min',
G: true
}))
.on('error', testErrorHandler);
});
gulp.task('watch', 'Watch files and run tests on change', function () {
gulp.watch('./lib/**/*.js', ['test-watch']);
});
With some guidance from #BrianGlaz I came up with the following task. Ends up being rather simple. Plus it pipes all output to the parent's stdout so I don't have to handle stdout.on manually:
// Run all unit tests in debug mode
gulp.task('test-debug', function () {
var spawn = require('child_process').spawn;
spawn('node', [
'--debug-brk',
path.join(__dirname, 'node_modules/gulp/bin/gulp.js'),
'test'
], { stdio: 'inherit' });
});
You can use Node's Child Process class to run command line commands from within a node app. In your case I would recommend childprocess.spawn(). It acts as an event emitter so you can subscribe to data to retrieve output from stdout. In terms of using this from within gulp, some work would probably need to be done to return a stream that could be piped to another gulp task.