Browserify not working properly in Gulp - javascript

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.

Related

Gulpfile not compiling Scss & JS properly

I am trying to create a gulpfile.js to compile scss to css and JS components to a main JS file. But it's not working properly.
The issues i am facing, when I run the command gulp:
It doesn't compile JS components to a main JS file.
It compiles SCSS but when i save any file, the git-bash terminal executing files infinitely, here is the screenshot:
Here is my gulpfile.js:
"use strict";
const source = 'assets/';
// Load Modules
const { src, dest, watch, series } = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const terser = require('gulp-terser');
const browsersync = require('browser-sync').create();
// Scss Task
function scssTask() {
return src(`${source}/scss/zaincss.scss`)
.pipe(sass())
.pipe(postcss([cssnano()]))
.pipe(dest(`${source}/css`));
}
// Javascript Task
function jsTask() {
return src(`${source}/js/scripts/*.js`)
.pipe(terser())
.pipe(dest(`${source}/js/scripts/`));
}
// BrowserSync Tasks
function browserSyncServe(done) {
browsersync.init({
server: {
baseDir: '.'
},
injectChanges: true
});
done()
}
function browserSyncReload(done) {
browsersync.reload();
done();
}
// Watch Task
function watchTask() {
watch('*.html', browserSyncReload);
watch(['assets/scss/**/*.scss', 'assets/js/**/*.js'], series(scssTask, jsTask, browserSyncReload));
}
// Default Gulp Task
exports.default = series(
scssTask, jsTask, browserSyncServe, watchTask
);
I have googled a lot, but i am stuck. Please help me.
Part of the problem is you are watching the same directory that you are storing your js files in:
// Javascript Task
function jsTask() {
return src(`${source}/js/scripts/*.js`)
.pipe(terser())
.pipe(dest(`${source}/js/scripts/`));
}
So you send the files to ${source}/js/scripts/ but you are watching that location in your watch task: 'assets/js/**/*.js'. So any change in that location starts the process all over again.
Store you minified js files someplace else than the same directory you are watching for changes.

Local changes to file in node_modules (Angular 2)

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']);

Why is Gulp not accessing my AppAPI.js file?

I am working on a project where I am using gulp. However, gulp keeps throwing an error saying it cannot find the AppAPI.js file in my work environment. I am building with Reactjs and Flux. I believe the problem may be in my gulpfile, but after trying various versions of the code, I have not been able to get anywhere. Could someone take a look and see if indeed my code is wrong or if there could be something else going wrong? Here is my gulpfile:
var gulp = require('gulp');
var browserify = require('browserify');
var reactify = require('reactify'); // Converts jsx to js
var source = require('vinyl-source-stream'); // Converts string to a stream
gulp.task('browserify', function(){
browserify('./src/js/main.js')
.transform('reactify')
.bundle()
.pipe(source('main.js'))
.pipe(gulp.dest('dist/js'));
});
gulp.task('copy', function(){
gulp.src('src/index.html')
.pipe(gulp.dest('dist'));
gulp.src('src/css/*.*')
.pipe(gulp.dest('dist/css'));
gulp.src('src/js/vendors/*.*')
.pipe(gulp.dest('dist/js'));
});
gulp.task('default', ['browserify', 'copy'], function(){
return gulp.watch('src/**/*.*', ['browserify', 'copy']);
});
I am requiring appAPI.js in my main.js file:
var App = require('./components/App');
var React = require('react');
var ReactDOM = require('react-dom');
var AppAPI = require('./utils/appAPI.js');
ReactDOM.render(
<App />,
document.getElementById('app')
);
Here is the appAPI.js code:
var AppActions = require('../actions/AppActions');
module.exports = {
}

Gulp-browserify Error

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
});

How to require Underscore templates with Browserify + Gulp

I'm setting up a Backbone project with Browserify & Gulp and can't seem to figure out how to require Underscore templates (not Handlebars) in my modules. The closest I've come is using "node-underscorify" (at least seeing something and no errors), but it's not quite right..
gulpfile.js
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var gulpif = require('gulp-if');
var sass = require('gulp-sass');
var env = process.env.NODE_ENV || 'dev';
gulp.task( 'js', function() {
var bundler = browserify({
entries: ['./dev/js/app.js'],
paths: ['./templates/'],
transform: ['node-underscorify']
});
return bundler
.bundle()
.pipe( source( 'bundle.js') )
.pipe( buffer() )
.pipe( gulpif( env === 'prod', uglify() ) )
.pipe( gulp.dest( './js/' ) );
});
home.html
<h3>Hello <%= name %></h3>
HomeView.js (compiled from CoffeeScript via a separate Gulp task)
(function() {
var $, Backbone, _;
$ = require('jquery');
_ = require('underscore');
Backbone = require('backbone');
Backbone.$ = $;
module.exports = Backbone.View.extend({
template: require('home.html'),
el: '#content',
initialize: function() {
console.log("home initialize");
this.render();
},
render: function() {
this.$el.html(this.template({
name: 'Gulp!'
}));
return this;
}
});
}).call(this);
When I run the app and it hits HomeView, the browser displays what looks like raw JS of the module, including the uncompiled template (?)
module.exports = function(obj){ var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');}; with(obj||{}){ __p+='
Hello '+ ((__t=( name ))==null?'':__t)+ '
\n\n'; } return __p; };
I tried applying the Underscore template function to the required file but that produces a JS error..
template: _.template( require('home.html') ),
Spent multiple hours perusing various blog posts, trying different solutions -- any help is much appreciated!
I was having the same problem. I finally got this working by building off of the example gulp recipe, but per Ben's comment, I explicitly call transform() on underscorify, instead of using the transform array.
I also choose to rename the bundled file along the way and output it in the same directory as the source.
Here's what my final working code looks like:
gulpfile.js
gulp = require("gulp");
browserify = require("browserify");
watchify = require("watchify");
underscorify = require("node-underscorify");
rename = require("gulp-rename");
source = require("vinyl-source-stream");
gutil = require("gulp-util");
mainBundler = watchify(browserify("./js/main.js"));
mainBundler.transform(underscorify.transform());
gulp.task("watchify-main", bundleMain);
mainBundler.on("update", bundleMain);
mainBundler.on("log", gutil.log);
function bundleMain() {
return mainBundler.bundle()
.on("error", gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source(".js/main.js"))
.pipe(rename("main-bundle.js"))
.pipe(gulp.dest("./js/"));
};
home.html
<h3>Hello <%= name %></h3>
main.js
template = require("./templates/home.html");
module.exports = Backbone.View.extend({
template : template,
el: "#content",
initialize: function() {
// initialize code
},
render: function() {
// render code
}
});

Categories

Resources