I want to apply react to my NodeJs
This is my gulpfile:
let gulp = require('gulp');
let uglify = require('gulp-uglify');
let browserify = require('browserify');
let babelify = require('babelify');
let source = require('vinyl-source-stream');
let buffer = require('vinyl-buffer');
let gutil = require('gulp-util');
let sourcemaps = require('gulp-sourcemaps');
let assign = require('lodash.assign');
let watchify = require('watchify');
let customOpts = {
entries : ['./App/app.js'],
extensive : ['.js'],
debug: true
};
let opts = assign({}, watchify.args, customOpts);
let b = watchify(browserify(opts));
gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal
function bundle() {
return b.transform(babelify,babelify.configure())
.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('app.js'))
// optional, remove if you don't need to buffer file contents
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('dest'));
}
gulp.task('default',['js']);
Then I intput gulp js
D:\weather-app>gulp js
[00:03:47] Using gulpfile D:\weather-app\gulpfile.js
[00:03:47] Starting 'js'...
[00:03:57] 2112196 bytes written (10.56 seconds)
[00:04:27] Finished 'js' after 41 s
The terminal got stuck here, I had to type Ctrl C to stop it.
Strangely, when I opened the index.html, the appearance changed.
So I don't know how could that be.
Related
When I am trying to save scss files which are imported to main sccs file - every time I need resave main scss file to apply changes. therefore I have decided to install gulp-sass-glob according to this https://www.npmjs.com/package/gulp-sass-glob
but unfortunately it does not work.
Here is my code, please help me how to integrate gulp-sass-glob in my gulp file or what is wrong here. Thank you.
const { src, dest, parallel, series, watch } = require('gulp');
// Load plugins
const sass = require('gulp-sass');
const browsersync = require('browser-sync').create();
const htmlmin = require('gulp-htmlmin');
// Directories
const SRC = './src/';
const DEST = './dist/';
const DEST_CSS = `${DEST}css/`;
const SRC_CSS = `${SRC}scss/*main.scss`;
var gulp = require('gulp');
var sassGlob = require('gulp-sass-glob');
gulp.task('styles', function () {
return gulp
.src(SRC_CSS)
.pipe(sassGlob())
.pipe(sass())
.pipe(gulp.dest(DEST_CSS));
});
// Watch files
function watchFiles() {
watch(`${SRC_CSS}*`, css);
watch(`${SRC}lang`, html);
}
// BrowserSync
function browserSync() {
browsersync.init({
server: {
baseDir: DEST
},
port: PORT
});
}
// Tasks to define the execution of the functions simultaneously or in series
exports.watch = series(
clear,
parallel( css, html, copyStaticHTML, watchFiles, browserSync)
);
exports.default = series(clear, parallel(js, css, html, copyStaticHTML));
I have this gulpfile:
var gulp = require('gulp'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify');
gulp.task('minifyJS', function() {
return gulp.src(['src/*.js'])
.pipe(uglify())
.pipe(gulp.dest('min'));
});
gulp.task('watch', function() {
gulp.watch(['src/*.js'], ['minifyJS']);
});
I want to know what file trigger the watcher and his absolute path.
For example: if my project is placed in /myCode and I change the file src/main.js, I want to see /myCode/src/main.js inside minifyJS task. Is there a way to do it?
Thank you for your time.
You can do it by using gulp-ng-annotate and gulp-changed:
var gulp = require('gulp');
var changed = require('gulp-changed');
var rename = require('gulp-rename');
var ngAnnotate = require('gulp-ng-annotate'); // just as an example
var SRC = 'src/*.js';
var DEST = 'src/';
//Function to get the path from the file name
function createPath(file) {
var stringArray = file.split('/');
var path = '';
var name = stringArray[1].split('.');
stringArray = name[0].split(/(?=[A-Z])/);
if (stringArray.length>1) {stringArray.pop()};
return {folder: stringArray[0], name: name[0]}
}
gulp.task('default', function () {
return gulp.src(SRC)
.pipe(changed(DEST))
// ngAnnotate will only get the files that
// changed since the last time it was run
.pipe(ngAnnotate())
.pipe(rename(function (path) {
var createdPath = createPath(path);
path.dirname = createdPath.folder;
path.basename: createdPath.name,
path.prefix: "",
path.suffix: "",
path.extname: ".min.js"
}))
.pipe(gulp.dest(DEST));
});
Result:
Use gulp-changed npm package.
$ npm install --save-dev gulp-changed
Try the below in gulp file, (I haven't tried)
var gulp = require('gulp'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
changed = require('gulp-changed');
gulp.task('minifyJS', function() {
return gulp.src(['src/*.js'])
.pipe(changed('min'))
.pipe(uglify())
.pipe(gulp.dest('min'));
});
gulp.task('watch', function() {
gulp.watch(['src/*.js'], ['minifyJS']);
});
see the documentation of this package https://www.npmjs.com/package/gulp-changed
Based on your comment to Julien's answer this should be fairly close to what you want, or at least get you going in the right direction:
var gulp = require('gulp'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
cache = require('gulp-cached'),
rename = require('gulp-rename'),
path = require('path');
function fileName(file) {
return file.dirname + path.sep + file.basename + file.extname;
}
gulp.task('minifyJS', function() {
return gulp.src(['src/*.js'])
.pipe(cache('minifyJS'))
.pipe(rename(function(file) {
var nameOfChangedFile = fileName(file);
if (nameOfChangedFile == './main.js') {
file.basename = 'main.min'
}
if (nameOfChangedFile == './userView.js') {
file.basename = 'user/userView.min'
}
console.log(nameOfChangedFile + ' -> ' + fileName(file));
}))
.pipe(uglify())
.pipe(gulp.dest('min'));
});
gulp.task('watch', function() {
gulp.watch(['src/*.js'], ['minifyJS']);
});
This uses gulp-cached to keep an in-memory cache of all the files in your src/ folder that have passed through the stream. Only files that have changed since the last invocation of minifyJS are passed down to the gulp-rename plugin.
The gulp-rename plugin itself is then used to alter the destination path of the changed files.
Note: the cache is empty on first run, since no files have passed through the gulp-cached plugin yet. This means that the first time you change a file all files in src/ will be written to the destination folder. On subsequent changes only the changed files will be written.
I am using gulp, browserify, watchify and factor bundle to build several javascript files in development. Everything works fine, excepts after some time I start seeing this warning:
Trace
at Browserify.addListener (events.js:179:15)
at f (/Users/benoit/git/figure/web/node_modules/factor-bundle/index.js:55:7)
at Browserify.plugin (/Users/benoit/git/figure/web/node_modules/browserify/index.js:345:9)
at Browserify.bundle (/Users/benoit/git/figure/web/gulpfile.js:46:13)
at Browserify.emit (events.js:107:17)
at null._onTimeout (/Users/benoit/git/figure/web/node_modules/watchify/index.js:126:15)
at Timer.listOnTimeout (timers.js:110:15)
(node) warning: possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
at ConcatStream.addListener (events.js:179:15)
at ConcatStream.once (events.js:204:8)
at Labeled.Readable.pipe (/Users/benoit/git/figure/web/node_modules/factor-bundle/node_modules/labeled-stream-splicer/node_modules/stream-splicer/node_modules/readable-stream/lib/_stream_readable.js:612:8)
at /Users/benoit/git/figure/web/node_modules/factor-bundle/index.js:73:43
at Array.reduce (native)
at Transform._flush (/Users/benoit/git/figure/web/node_modules/factor-bundle/index.js:65:35)
at Transform.<anonymous> (/Users/benoit/git/figure/web/node_modules/factor-bundle/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:135:12)
at Transform.g (events.js:199:16)
at Transform.emit (events.js:129:20)
at finishMaybe (/Users/benoit/git/figure/web/node_modules/factor-bundle/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:371:12)
at endWritable (/Users/benoit/git/figure/web/node_modules/factor-bundle/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:378:3)
at Transform.Writable.end (/Users/benoit/git/figure/web/node_modules/factor-bundle/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:356:5)
(node) warning: possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit.
Below is my gulpfile
var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var reactify = require('reactify');
var watchify = require('watchify');
var factor = require('factor-bundle');
var uglify = require('gulp-uglify');
var fs = require('fs');
var concat = require('concat-stream');
var file = require('gulp-file');
gulp.task('watch', bundle)
function bundle () {
// react components
var files = [
'/path/to/file1.jsx',
'/path/to/file2.jsx',
'/path/to/file3.jsx'
];
var bundler = watchify(browserify(watchify.args))
bundler.add(files);
bundler.add('./lib/api.js', {expose: 'api'});
bundler.require('./lib/api.js', {expose: 'api'});
bundler.transform('reactify');
bundler.on('update', rebundle);
function rebundle() {
bundler.plugin('factor-bundle', {
outputs: [
write('/path/to/file1.js'),
write('/path/to/file2.js'),
write('/path/to/file3.js'),
]
});
bundler.bundle()
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(write('shared.js'));
};
return rebundle();
}
function write (name) {
return concat(function (content) {
// create new vinyl file from content and use the basename of the
// filepath in scope as its basename.
return file(name, content, { src: true })
// uglify content
.pipe(uglify())
// write content to build directory
.pipe(gulp.dest('./public/bundles/'))
});
}
I read I should set max listeners somewhere but I am afraid this might be a geniune memory leak.
My initial solution didn't work, and it looks like it really is a bug. I think I've found a temporary hacky fix though.
Edit node_modules/factor-bundle/index.js and change
From
b.on('reset', addHooks);
to
b.once('reset', addHooks);
Your original code should work.
Here's the GitHub issue for anyone who's keeping score :D
I tried to uglify output of Browserify in Gulp, but it doesn't work.
gulpfile.js
var browserify = require('browserify');
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var source = require('vinyl-source-stream');
gulp.task('browserify', function() {
return browserify('./source/scripts/app.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(uglify()) // ???
.pipe(gulp.dest('./build/scripts'));
});
As I understand I cannot make it in steps as below. Do I need to make in one pipe to preserve the sequence?
gulp.task('browserify', function() {
return browserify('./source/scripts/app.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(uglify()) // ???
.pipe(gulp.dest('./source/scripts'));
});
gulp.task('scripts', function() {
return grunt.src('./source/scripts/budle.js')
.pipe(uglify())
.pipe(gulp.dest('./build/scripts'));
});
gulp.task('default', function(){
gulp.start('browserify', 'scripts');
});
You actually got pretty close, except for one thing:
you need to convert the streaming vinyl file object given by source() with vinyl-buffer because gulp-uglify (and most gulp plugins) works on buffered vinyl file objects
So you'd have this instead
var browserify = require('browserify');
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
gulp.task('browserify', function() {
return browserify('./source/scripts/app.js')
.bundle()
.pipe(source('bundle.js')) // gives streaming vinyl file object
.pipe(buffer()) // <----- convert from streaming to buffered vinyl file object
.pipe(uglify()) // now gulp-uglify works
.pipe(gulp.dest('./build/scripts'));
});
Or, you can choose to use vinyl-transform instead which takes care of both streaming and buffered vinyl file objects for you, like so
var gulp = require('gulp');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var uglify = require('gulp-uglify');
gulp.task('build', function () {
// use `vinyl-transform` to wrap the regular ReadableStream returned by `b.bundle();` with vinyl file object
// so that we can use it down a vinyl pipeline
// while taking care of both streaming and buffered vinyl file objects
var browserified = transform(function(filename) {
// filename = './source/scripts/app.js' in this case
return browserify(filename)
.bundle();
});
return gulp.src(['./source/scripts/app.js']) // you can also use glob patterns here to browserify->uglify multiple files
.pipe(browserified)
.pipe(uglify())
.pipe(gulp.dest('./build/scripts'));
});
Both of the above recipes will achieve the same thing.
Its just about how you want to manage your pipes (converting between regular NodeJS Streams and streaming vinyl file objects and buffered vinyl file objects)
Edit:
I've written a longer article regarding using gulp + browserify and different approaches at: https://medium.com/#sogko/gulp-browserify-the-gulp-y-way-bb359b3f9623
Two additional approaches, taken from the vinyl-source-stream NPM page:
Given:
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var browserify = require('browserify');
var uglify = require('gulp-uglify');
var gulpify = require('gulpify');
var gulp = require('gulp');
Approach 1 Using gulpify (deprecated)
gulp.task('gulpify', function() {
gulp.src('index.js')
.pipe(gulpify())
.pipe(uglify())
.pipe(gulp.dest('./bundle.js'));
});
Approach 2 Using vinyl-source-stream
gulp.task('browserify', function() {
var bundleStream = browserify('index.js').bundle();
bundleStream
.pipe(source('index.js'))
.pipe(streamify(uglify()))
.pipe(gulp.dest('./bundle.js'));
});
One benefit of the second approach is that it uses the Browserify API directly, meaning that you don't have to wait for the authors of gulpify to update the library before you can.
you may try browserify transform uglifyify.
I'm trying to get my head around gulp to watch and compile a .less project + livereload.
I have a style.less file which use #import.
When i run the gulp task it doesn't seem to understand the imports. When I modify the main less file, gulp compiles the file and refresh the browser but if i modify only an import, the changes are ignored.
Here is my gulpfile.js
var gulp = require('gulp');
var less = require('gulp-less');
var watch = require('gulp-watch');
var prefix = require('gulp-autoprefixer');
var plumber = require('gulp-plumber');
var livereload = require('gulp-livereload');
var path = require('path');
gulp.task('default', function() {
return gulp.src('./style.less')
.pipe(watch())
.pipe(plumber())
.pipe(less({
paths: ['./', './overrides/']
}))
.pipe(prefix("last 8 version", "> 1%", "ie 8", "ie 7"), {cascade:true})
.pipe(gulp.dest('./'))
.pipe(livereload());
});
I tried not specifying the main file name in gulp.src('./*.less') but then all of the less files are compiled indvidually.
Thanks
Right now you are opening the single gulp.src file, and watching After you open the file with gulp.
The following will split the watching and src into two tasks, allowing for separate file and src watching.
var gulp = require('gulp');
var less = require('gulp-less');
var watch = require('gulp-watch');
var prefix = require('gulp-autoprefixer');
var plumber = require('gulp-plumber');
var livereload = require('gulp-livereload');
var path = require('path');
gulp.task('less', function() {
return gulp.src('./style.less') // only compile the entry file
.pipe(plumber())
.pipe(less({
paths: ['./', './overrides/']
}))
.pipe(prefix("last 8 version", "> 1%", "ie 8", "ie 7"), {cascade:true})
.pipe(gulp.dest('./'))
.pipe(livereload());
});
gulp.task('watch', function() {
gulp.watch('./*.less', ['less']); // Watch all the .less files, then run the less task
});
gulp.task('default', ['watch']); // Default will run the 'entry' watch task
When Any of the files found with *.less are altered it will then run the task which will compile just the src file.
The #imports should be 'included' correctly, if not check the import settings.