How to bundle multiple files in nested directory in gulp? - javascript

I am using gulp and what I need to do is to bundle all the files in multiple nested directories in node_modlues folder to public/js/libName and dist/js/libName so that I can use that module in my client.
dist
js
node_modules
test_library
file1.js
file2.js
folder1
file1.js
file2.js
folder2
file3.js
file4.js
public
js

I recently solved similar task this way:
require:
src/bundle_entrypoint.js (bundle entrypoint):
require('jquery');
// your code
gulpfile:
// init base modules
// additional modules
var source = require('vinyl-source-stream');
var browserify = require('browserify');
// reg build tasks, etc
gulp.task('build-bundle', function() {
return browserify({
entries: 'src/bundle_entrypoint.js',
debug: true,
paths: ['./node_modules'],
cache: {},
packageCache: {}
})
.bundle()
.pipe(source('bundle.js'))
.pipe(uglifyOrWhateverYouWant())
.pipe(gulp.dest('public/js/'))
.pipe(gulp.dest('dist/js/'));
});
EDIT:
concat:
gulp.task('build-bundle', function() {
return gulp.src(['node_modules/test_library/**/*.js','src/my.js'])
.pipe(concat('bundle.js'))
.pipe(uglifyOrWhateverYouWant())
.pipe(gulp.dest('public/js/'))
.pipe(gulp.dest('dist/js/'));
});

Related

Jquery library not working after gulp bundle

I am quite a newbie for gulp but i am trying to implement it in my this project. But looks like somewhere i mashup. I order the js files and was trying to get the bundle. But looks like jquery lib or something is not working.
Here is my gulpfile.js code:
'use strict';
// include all necessary plugins in gulp file
var gulp = require('gulp');
var order = require('gulp-order');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
// Task defined for java scripts bundling and minifying
gulp.task('scripts', function() {
return gulp.src('assets/src/js/*.js')
.pipe(order([
"assets/src/js/jquery-3.2.1.slim.min.js",
"assets/src/popper.min.js",
"assets/src/js/bootstrap.min.js",
"assets/src/js/morphext.min.js",
"assets/src/js/pushy.min.js",
"assets/src/quote.js"
], { base: './' }))
.pipe(concat('bundle.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('assets/dist/js'));
});
// Task define for compliling scss file
// Currently i am not using this complier
gulp.task('sass', function() {
return gulp.src('assets/src/css/**/*.scss', {style: 'compressed'})
.pipe(rename({suffix: '.min'}))
.pipe(sourcemaps.init()) // Process the original sources
.pipe(sass())
.pipe(sourcemaps.write()) // Add the map to modified source.
.pipe(gulp.dest('assets/dist/css/'));
});
// Define task to optimize images in project
gulp.task('images', function() {
return gulp.src('assets/src/img/**/*')
.pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
.pipe(gulp.dest('assets/dist//img'));
});
// Task watch
gulp.task('watch', function() {
// Watch .js files
gulp.watch('assets/src/js/*.js', ['scripts']);
// Watch .scss files
gulp.watch('assets/src/css/*.scss', ['sass']);
// Watch image files
gulp.watch('assets/src/img/**/*', ['images']);
});
// declaring final task and command tasker
// just hit the command "gulp" it will run the following tasks...
gulp.task('default', ['scripts', 'images' , 'watch']);
I got solution for this problem, here is my new code for gulp.js!
'use strict';
// include all necessary plugins in gulp file
var gulp = require('gulp');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
// Task defined for java scripts bundling and minifying
gulp.task('scripts', function() {
return gulp.src
([
'assets/src/js/jquery/*.js',
'assets/src/js/vendor/*.js',
'assets/src/js/plugins/*.js',
'assets/src/js/custom/*.js',
])
.pipe(concat('bundle.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('assets/dist/js/'));
});
// Task define for compliling scss file
gulp.task('sass', function() {
return gulp.src('assets/src/scss/**/*.scss', {style: 'compressed'})
.pipe(rename({suffix: 'custom'}))
.pipe(sourcemaps.init()) // Process the original sources
.pipe(sass())
.pipe(sourcemaps.write()) // Add the map to modified source.
.pipe(gulp.dest('assets/dist/css/unminified/'));
});
// Define task to optimize images in project
gulp.task('images', function() {
return gulp.src('assets/src/img/**/*')
.pipe(cache(imagemin({ optimizationLevel:5, progressive: true, interlaced: true })))
.pipe(gulp.dest('assets/dist/img'));
});
// Task watch
gulp.task('watch', function() {
// Watch .js files
gulp.watch('assets/src/js/*.js', ['scripts']);
// Watch .scss files
gulp.watch('assets/src/scss/*.scss', ['sass']);
// Watch image files
gulp.watch('assets/src/img/**/*', ['images']);
});
// declaring final task and command tasker
// just hit the command "gulp" it will run the following tasks...
gulp.task('default', ['scripts', 'images' , 'sass' , 'watch']);

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

Update: Errors with postCSS and Babel in Gulpfile

Goal
I'm updating my old gulpfile.js, which used to be mainly for compiling my Sass into CSS, but now I'm trying to get Gulp to do the following:
Sync browser, whip up localhost server - DONE
Compile Sass => CSS - DONE
Show any JavaScript errors with JSHint - DONE
Compile ES6 => ES6 with Babel (WORKING ON)
Minify all assets (WORKING ON)
Show project file size - DONE
Deploy index.html, style.css and images to S3 (WORKING ON)
Watch files, reload browser when .scss or .html changes - DONE
Problem
Trying to minify my Javascript and also create a scripts.min.js
file, it keeps adding the suffix min to every new minified JavaScript
file.
Folder structure
index.html
gulpfile.js
package.json
.aws.json
.csscomb.json
.gitignore
assets
- css
style.css
style.scss
--partials
---base
---components
---modules
- img
- js
scripts.js
- dist
gulpfile.js
// Include Gulp
var gulp = require('gulp');
var postcss = require("gulp-postcss");
// All of your plugins
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync');
var cache = require('gulp-cache');
var concat = require('gulp-concat');
var csswring = require("csswring");
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lost = require("lost");
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var rucksack = require("rucksack-css");
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
// Sync browser, whip up server
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// Reload page automagically
gulp.task('bs-reload', function () {
browserSync.reload();
});
// Compile Sass into CSS, apply postprocessors
gulp.task('styles', function(){
var processors = [
autoprefixer({browsers: ['last 2 version']}),
csswring,
lost,
rucksack
];
gulp.src(['assets/css/**/*.scss'])
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(sass())
.pipe(postcss(processors))
// .pipe(gulp.dest('assets/css/'))
// .pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('assets/css/'))
.pipe(browserSync.reload({stream:true}))
});
// Show any JavaScript errors
gulp.task('scripts', function(){
return gulp.src('assets/js/**/*.js')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(jshint())
.pipe(jshint.reporter('default'))
// .pipe(concat('main.js'))
// .pipe(babel())
.pipe(gulp.dest('assets/js/'))
.pipe(uglify())
.pipe(gulp.dest('assets/js/'))
.pipe(rename({suffix: '.min'}))
.pipe(browserSync.reload({stream:true}))
});
// Minify assets, create build folder
gulp.task('images', function(){
gulp.src('assets/img/**/*')
.pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
.pipe(gulp.dest('assets/img'));
});
// Minify HTML
// Default task
gulp.task('default', ['browser-sync'], function(){
gulp.watch("assets/css/**/*.scss", ['styles']);
gulp.watch("assets/js/**/*.js", ['scripts']);
gulp.watch("*.html", ['bs-reload']);
gulp.start("images", "styles", "scripts")
});
// var babel = require('gulp-babel');
// var minifyhtml = require("gulp-minify-html");
// var size = require("gulp-size");
// var upload = require("gulp-s3");
Hi i can't solve all your problems but I had also a similar issue with the babel and ES6 fat arrow functions (using babelify and browserify). To solve the problem try to pass:
stage: 0
to your babel.js gulp plugin. If error will still occurs then try to pass also:
experimental: true
For more information please have a look "experimental" section on babel.js site.

How can I bundle js files in my lib with main app.js

Right now, only my app.js and the files that I use inside it are being bundled. I want the files inside my libs to also be bundled together into that same js file. Here is my folder structure inside my js folder:
.
├── app.js
├── components
└── libs
└── materialize.min.js
And here is my gulpfile where I'm bundling them all together:
import gulp from 'gulp'
import source from 'vinyl-source-stream'
import buffer from 'vinyl-buffer'
import browserify from 'browserify'
import babelify from 'babelify'
import uglify from 'gulp-uglify'
import watchify from 'watchify'
const jsDirs = {
src: './client/js/app.js',
dest: './dist/js'
}
function buildBundle(b) {
b.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest(jsDirs.dest))
}
gulp.task('scripts', () => {
let b = browserify({
cache: {},
packageCache: {},
fullPaths: true
})
b = watchify(b.transform(babelify))
b.on('update', () => buildBundle(b))
b.add(jsDirs.src)
buildBundle(b)
})
gulp.task('default', ['scripts'])
Is there any way to include my libs js files which aren't being used by app.js?
you should be able to call b.require(path) multiple times. (that's how I do it for mine)
Something like :
import gulp from 'gulp'
import source from 'vinyl-source-stream'
import buffer from 'vinyl-buffer'
import browserify from 'browserify'
import babelify from 'babelify'
import uglify from 'gulp-uglify'
import watchify from 'watchify'
const jsDirs = {
src: './client/js/app.js',
dest: './dist/js',
requires: [
'./libs/materialize.min.js',
['./libs/whatever.js', 'whatever']
]
}
function buildBundle(b) {
b.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest(jsDirs.dest))
}
gulp.task('scripts', () => {
let b = browserify({
cache: {},
packageCache: {},
fullPaths: true
});
b = watchify(b.transform(babelify))
[].concat(jsDirs.requires || []).forEach(function (req) {
var path = req,
expose = null;
if (typeof path !== 'string') {
expose = path[1];
path = path[0]
}
b.require(path, expose ? { expose: expose } : {});
});
b.on('update', () => buildBundle(b))
b.add(jsDirs.src)
buildBundle(b)
})
gulp.task('default', ['scripts'])
this also let you expose the lib for futur requires

Prevent browserify from including module's dependencies

I'd like to use my NodeJS module in the browser - so I'm using browserify to process it.
Now, how can I stop browserify from including the module's dependencies in the bundle file? In this case the dependency is lodash and I'll be loading it separately in the index.html.
Here's what I've got so far:
index.html
<script src="lodash.js"></script>
<script src="my-module.js"></script>
index.js
var _ = require('lodash');
_.each([0, 1, 2], function(item) {
console.log(item);
});
gulp.js
var browserify = require('browserify'),
source = require('vinyl-source-stream');
gulp.task('browserify', function() {
return browserify()
.require('./index.js', {
expose: 'my-module'
})
.bundle()
.pipe(source('my-module.js'))
.pipe(gulp.dest('./'));
});
browserify-shim offers the option of setting up globals.
Here are the changes I've made to my code.
package.json
{
"browserify-shim": {
"lodash": "global:_"
},
"browserify": {
"transform": ["browserify-shim"]
}
}
gulp.js
gulp.task('browserify', function() {
return browserify('./index.js')
.require('./index.js', {
expose: 'my-module'
})
.transform('browserify-shim', {
global: true
})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./'));
});
There's an option to exclude files:
Usage: browserify [entry files] {OPTIONS}
[...]
--ignore, -i Replace a file with an empty stub. Files can be globs.
--exclude, -u Omit a file from the output bundle. Files can be globs.
https://github.com/substack/node-browserify#usage
And the corresponding exclude function:
b.exclude(file)
Prevent the module name or file at file from showing up in the output bundle.
If your code tries to require() that file it will throw unless you've provided another mechanism for loading it.
So you should try this:
return browserify()
.require('./index.js', {
expose: 'my-module'
})
.exclude('lodash.js')
.bundle();
I figured this out.
const nodeOnlyModule = eval('require')('module-name');
This way you can trick browserify.

Categories

Resources