Use glob matching, when passing files to browserify in gulp - javascript

All the examples I have seen using browserify and gulp assume that you only want to browserify 1 file. This is usually not the case.
I came across an example that used vinyl-transforms, but I am unable to get it to work correctly. Here is the (coffee-script) code:
# Browserify JS
gulp.task 'browserify', [], ->
# Create the transform
br = transform (f) ->
return browserify(f).bundle()
# Run browserify
gulp.src(['./public/js/**/*.js'])
.pipe(br)
.pipe(gulp.dest('.'))
But I get the following error:
[10:50:55] Starting 'browserify'...
events.js:72
throw er; // Unhandled 'error' event
^
Error: write after end

The easiest way would be to use glob directly:
var glob = require('glob');
gulp.task('browserify', function() {
var files = glob.sync('./public/js/**/*.js');
return browserify({entries: files})
.bundle()
.pipe(gulp.dest('.'));
});

Related

Gulp Task completes with no error but no file is saved to destination

i am stuck in a kind of a trivial issue and can not get a hang of it.
here is the scenario:
I am using Gulp Task to convert my html templates to javascript using gulp-html2js My environment is Node v6.9.1, gulp 3.9.1, Windows 7
here is the gulpfile.js
var gulp = require('gulp');
var concat = require('gulp-concat');
var html2js = require('gulp-html2js');
var sourceDir = "D:\Programs_Insalled\nodejs\nodeapps\myApp"
gulp.task('templates', function() {
return gulp.src( 'D:\Programs_Insalled\nodejs\nodeapps\myApp\templates\*.html').
pipe(html2js({outputModuleName: 'templates'})).
pipe(concat('templates.js')).
pipe(gulp.dest('D:\Programs_Insalled\nodejs\nodeapps\myApp\bin'));
});
when i run the task, it completes, in a few m-sec but templates.js is not generated in bin directory
D:\Programs_Insalled\nodejs\nodeapps\myApp>gulp templates
[15:28:45] Using gulpfile D:\Programs_Insalled\nodejs\nodeapps\myApp\gulpfile.js
[15:28:45] Starting 'templates'...
[15:28:45] Finished 'templates' after 19 ms
I have tried below suggestions in similar items listed on GitHub and stackoverflow but have not been successful,
https://github.com/yeoman/generator-webapp/issues/182
https://github.com/yeoman/generator-webapp/issues/225
Can someone help out to find my mistake.
Thanks.
EDIT output of provided examples:
D:\Programs_Insalled\nodejs\nodeapps\myApp>gulp models
[17:13:10] Using gulpfile D:\Programs_Insalled\nodejs\nodeapps\myApp\gulpfile.js
[17:13:10] Starting 'models'...
[17:13:10] Finished 'models' after 21 ms
D:\Programs_Insalled\nodejs\nodeapps\myApp>gulp templates
[17:13:13] Using gulpfile D:\Programs_Insalled\nodejs\nodeapps\myApp\gulpfile.js
[17:13:13] Starting 'templates'...
D:\Programs_Insalled\nodejs\nodeapps\myApp\node_modules\vinyl\index.js:120
if (!this.path) throw new Error('No path specified! Can not get relative.');
^
Error: No path specified! Can not get relative.
at File.get (D:\Programs_Insalled\nodejs\nodeapps\myApp\node_modules\vinyl\index.js:120:27)
at DestroyableTransform.bufferContents [as _transform] (D:\Programs_Insalled\nodejs\nodeapps\myA
pp\node_modules\gulp-concat\index.js:70:20)
at DestroyableTransform.Transform._read (D:\Programs_Insalled\nodejs\nodeapps\myApp\node_modules
\gulp-concat\node_modules\readable-stream\lib\_stream_transform.js:184:10)
at DestroyableTransform.Transform._write (D:\Programs_Insalled\nodejs\nodeapps\myApp\node_module
s\gulp-concat\node_modules\readable-stream\lib\_stream_transform.js:172:12)
at doWrite (D:\Programs_Insalled\nodejs\nodeapps\myApp\node_modules\gulp-concat\node_modules\rea
dable-stream\lib\_stream_writable.js:237:10)
at writeOrBuffer (D:\Programs_Insalled\nodejs\nodeapps\myApp\node_modules\gulp-concat\node_modul
es\readable-stream\lib\_stream_writable.js:227:5)
at DestroyableTransform.Writable.write (D:\Programs_Insalled\nodejs\nodeapps\myApp\node_modules\
gulp-concat\node_modules\readable-stream\lib\_stream_writable.js:194:11)
at DestroyableTransform.ondata (D:\Programs_Insalled\nodejs\nodeapps\myApp\node_modules\through2
\node_modules\readable-stream\lib\_stream_readable.js:531:20)
at emitOne (events.js:96:13)
at DestroyableTransform.emit (events.js:188:7)
D:\Programs_Insalled\nodejs\nodeapps\myApp>
. for pipe is better before pipe, I give you an e.g of one of my gulpile and you not need to put absolute machine path in dest your gulpfile is a root path of task gulp work with js use js path try this
Inever use html2js I dont know if you syntax is correct but first try with this path
my e.g
gulp.task('models', function(){
return gulp.src('models/*.*')
.pipe(gulp.dest('../dist/models'))
});
try that for you
gulp.task('templates', function() {
return gulp.src( 'templates/*.html')
.pipe(html2js({outputModuleName: 'templates'}))
.pipe(concat('templates.js'))
.pipe(gulp.dest('bin'))
});
So, i have finally worked out the solution, Alhamdolilah
Issue was not with gulp task, or html2js, real issue was with gulp-concat
and i have realized that it is not needed as output is already concatenated by html2js
here is improved code:
gulp.task('templates', function () {
gulp.src('templates/*.html')
.pipe(html2js('templates.js', {
outputModuleName: 'templates',
name: 'templates'
}))
.pipe(gulp.dest('bin/'));
});

Gulp location of unhandled error in events.js:141

When I run task for example using comman gulp scripts:common, I get this output:
[14:05:47] Requiring external module babel-core/register
[14:05:49] Using gulpfile /home/sites/blablabla/gulpfile.babel.js
[14:05:49] Starting 'scripts:common'...
events.js:141
throw er; // Unhandled 'error' event
^
SyntaxError: Unexpected token
Well, for SyntaxError it would be useful to know where it found that unexpected token. How to tell it to show at least file and line? Where to find that evetns.js file? Could I put console.trace() or something like that there?
I solve this problem by running jshint on my scripts:
/*
* `gulp check_scripts` - Lints script files
*/
gulp.task('check_scripts', function() {
return gulp.src([
'gulpfile.js' //, other scripts to check
])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
enabled.failJSHint is there to allow errors to pass in local environment but fail in production.
This will lint any syntax errors in your scripts.
Additionally you may want to hook it to other task so it's run automatically before proper build:
gulp.task('default', ['check_scripts', 'clean'], function() {
gulp.start('build');
});
This is the general idea.
You can look at error stack trace by adding custom "on error" handler to the gulp task.
gulp.task('compile:js', function() {
return (
gulp.src(jsPath)
.pipe(yourCustomTask())
.on('error', function(err) {
console.log(err.stack);
this.end();
})
);
});
Also, as another variant, adding gulp-plumber into pipeline makes error messages more clear.

Typescript module, require external node_modules

I need to use a simple node_module inside a simple typescript file, but it seems that the compiler doesn't want to get it.
Here's my simple ts file :
import glob = require('glob');
console.log(glob);
And I've got this error :
[13:51:11] Compiling TypeScript files using tsc version 1.5.0
[13:51:12] [tsc] > F:/SkeletonProject/boot/ts/Boot.ts(4,23): error TS2307: Cannot find external module 'glob'.
[13:51:12] Failed to compile TypeScript: Error: tsc command has exited with code:2
events.js:72
throw er; // Unhandled 'error' event
^
Error: Failed to compile: tsc command has exited with code:2
npm ERR! skeleton-typescript-name#0.0.1 start: `node compile && node ./boot/js/Boot.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the skeleton-typescript-name#0.0.1 start script.
However, when I use a simple declaration in this same script, it works :
var x = 0;
console.log(x); // prints 0 after typescript compilation
What am I doing wrong in this case ?
EDIT:
Here's my gulp file :
var gulp = require('gulp');
var typescript = require('gulp-tsc');
gulp.task('compileApp', ['compileBoot'], function () {
return gulp.src(['app/src/**/*.ts'])
.pipe(typescript())
.pipe(gulp.dest('app/dist/'))
});
gulp.task('compileBoot', function () {
return gulp.src(['boot/ts/*.ts'])
.pipe(typescript({
module:'commonjs'
}))
.pipe(gulp.dest('boot/js/'))
});
gulp.start('compileApp');
Thanks for advance
Thanks for advance
You are using the correct syntax:
import glob = require('glob');
But the error: Cannot find external module 'glob' is pointing out that you are using a special case.
By default, the compiler is looking for glob.ts, but in your case you are using a node module, not a module that you have written. For this reason, the glob module will need special treatment...
If glob is a plain JavaScript module, you can add a file named glob.d.ts with type information that described the module.
glob.d.ts
declare module "glob" {
export class Example {
doIt(): string;
}
}
app.ts
import glob = require('glob');
var x = new glob.Example();
Some Node modules already include the .d.ts in the package, in other cases you can grab it from Definitely Typed.
Here is the error with your code
import glob = require('glob');
Because in node.js import is not a reserved keyword. If you require any module in your application, you simply require it using the statement
var glob = require('glob');
Once done you can then use
console.log(glob);
To print the value of glob.Replacing import will hopefully do the job for you.

gulp-uncss 'TypeError' undefined when used with gulp-if

I started loving gulp but I've been having too many cryptic errors that are very hard to find and at the end I'm working for my gulpfile.js instead of doing my job.
Anyway, I tried gulp-uncss before, outside gulp-useref and therefore outside gulp-if, but my gulpfile.js ended up too bulky and unreadable. Now it's readable but it doesn't work. Hurray.
var p = require('gulp-load-plugins')();
gulp.task('html', function () {
var assets = p.useref.assets();
gulp.src('*.html')
.pipe(assets)
.pipe(p.if('*.js', p.uglify()))
.pipe(p.if('*.css', p.uncss()))
.pipe(assets.restore())
.pipe(p.useref())
.pipe(gulp.dest(build_folder))
.pipe(p.size());
});
That generates this:
[12:47:53] /long/path/web $ gulp html
[12:48:06] Using gulpfile /long/path/web/gulpfile.js
[12:48:06] Starting 'html'...
[12:48:07] 'html' errored after 507 ms
[12:48:07] TypeError: Cannot set property 'ignoreSheets' of undefined
at Object.module.exports (/long/path/web/node_modules/gulp-uncss/index.js:14:26)
at Gulp.<anonymous> (/long/path/web/gulpfile.js:45:31)
at module.exports (/long/path/web/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/long/path/web/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep (/long/path/web/node_modules/gulp/node_modules/orchestrator/index.js:214:10)
at Gulp.Orchestrator.start (/long/path/web/node_modules/gulp/node_modules/orchestrator/index.js:134:8)
at /usr/local/lib/node_modules/gulp/bin/gulp.js:129:20
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
[12:48:12] /long/path/web $
Uncss was crucial to my workflow and I can't crack what's going wrong here. Any clue?
EDIT: This is what's in /long/path/web/node_modules/gulp-uncss/index.js until line 14
'use strict';
var uncss = require('uncss'),
gutil = require('gulp-util'),
assign = require('object-assign'),
transform = require('stream').Transform,
PLUGIN_NAME = 'gulp-uncss';
module.exports = function(options) {
var stream = new transform({ objectMode: true });
// Ignore stylesheets in the HTML files; only use those from the stream
options.ignoreSheets = [/\s*/];
Well, your excerpt of gulp-uncss/index.js states, that it can not handle an undefined options parameter - which it is not in you gulpfile:
.pipe(p.if('*.css',
p.uncss({
html: [ '*.html' ] // html files to check for styles to keep
})
))
The doc also states, that html is an required option attribute: npmjs.com/package/gulp-uncss#html
Type: Array|String Required value.
An array which can contain an array of files relative to your gulpfile.js, and which can also contain URLs. Note that if you are to pass URLs here, then the task will take much longer to complete. If you want to pass some HTML directly into the task instead, you can specify it here as a string.

configuring requirejs reading from node_modules

I'm trying to setup a nodejs project to use requirejs. I call my program with node r.js ./config/main.js and my main.js looks like the following:
var cs = require("coffee-script");
var requirejs = require("requirejs");
requirejs.config({
nodeRequire: require,
baseUrl: ".",
paths: {
cs: "cs",
CoffeeScript: "CoffeeScript",
csBuild: "csBuild",
express: "express",
nohm: "nohm",
redback: "redback",
_: "underscore",
"connect-redis": "connect-redis",
freebase: "freebase"
}
});
console.log("hetet");
requirejs(["cs!./config/app"], function(app){
console.log("closing")
});
and inside app.coffee:
define((require) ->
express = require("express")
RedisStore = require("connect-redis")(express)
app = express.createServer()
config = require('cs!./config')
require('cs!./setup')(app, express, RedisStore)
require('cs!./routes')(app)
require('cs!../src/server')
app.listen(config.server.port)
)
I seem to fail in main.js with the error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Calling node's require("config") failed with error: Error: Calling node's require("config") failed with error: Error: Cannot find module 'config'
and What I have noticed is when I comment out the line var requirejs = require("requirejs"); (in main.js), I get further and fail at the line RedisStore = require("connect-redis")(express) (in app.coffee) with the error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: undefined is not a function
at ./config/app.coffee:10:41
I have been having a lot of trouble configuring requirejs in node any help would be appreciated.
thanks
It is best to not configure requirejs to look in node_modules, since modules in that area are modules formatted for node. There is a little bit more info in the requirejs node page.

Categories

Resources