Combine gulp tasks to avoid creating the unnecessary files - javascript

I'm using two separate gulp tasks to minify templates into js file (1) and concat all js file of the project to the only minified (2).
gulp.task('templates', function() { // RESULT of this task
return gulp.src('templates/**/*.html')
.pipe(dotify({
root : 'templates'
}))
.pipe(concat('templates.js'))
.pipe(gulp.dest('js'));
});
gulp.task('minifyJs', ['templates'], function() {
return gulp.src([
'js/templates.js',
'js/plugins/*.js',
'js/*.js'
])
.pipe(concat('scripts-all.js'))
});
The question is: am I able to avoid creating the templates.js file by processing the result from first task to the second one to concat it with the rest of js's?

Solution: addSrc should be used
return gulp.src('templates/**/*.html')
.pipe(dotify({
root : 'templates'
}))
.pipe(addSrc([
'js/plugins/*.js',
'js/common/*.js',
'js/ui/*.js',
'js/pages/*.js',
'js/*.js'
]))
.pipe(concat('scripts-all.js'))
.pipe(gulp.dest('js/'));

Related

Gulp. How to generate 2 separate JS files with gulp build

I have 2 separate script files for 2 different html pages. like this
-/src
-/pages
-main.html
-info.html
-/js
-main.js
-info.js
I need gulp to generate 2 separate JS files from /src folder to /public folder.
Here's my script task:
function scripts() {
return src('./src/js/main.js')
.pipe(
includeFiles({
includePaths: './src/components/**/',
})
)
.pipe(dest('./public/js/'))
.pipe(browserSync.stream())
}
I realize it could be done through a cycle. Just can't figure out how exactly. I tried this , but didn't work
let scripts = ['./src/js/index.js','./src/js/info.js']
function handleScripts(){
scripts.forEach( link => {
return src(link)
.pipe(
includeFiles({
includePaths: './src/components/**/',
})
)
.pipe(dest('./public/js/'))
.pipe(browserSync.stream())
})
}

How to run function before run task in gulp?

guys how to run another function in task before run main task? AS u can see in function have stream, and i know about syntax (gulp.task('task', ['tast'], func... ) But i dont want to see 999 tasks in list, thats why im trying to use functions for tasks
function cssBuild() {
var dt = gulp
.src('app/html-dev/styl/framework/style.styl')
.pipe(plumber({ errorHandler: onError }))
.pipe(stylus({ use: nib(), 'include css': true, import: ['nib'], compress: false }))
.pipe(gulp.dest('app/cache/css'))
.pipe(browserSync.stream());
return dt;
}
function htmlBuild() {
var dt = gulp
.src('app/html-dev/**/*.pug')
.pipe(plumber({ errorHandler: onError }))
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('app/cache'))
.pipe(browserSync.stream());
return dt;
}
gulp.task('build', function() {
var removeDist = del.sync('app/dist');
cssBuild();
htmlBuild();
jsBuild();
return merge (
gulp
.src('app/cache/css/*.css')
.pipe(cssnano())
.pipe(gulp.dest('app/dist/css')),
gulp
.src(['app/html-dev/img/**/*', '!app/html-dev/img/empty.jpg'])
.pipe(gulp.dest('app/dist/img')),
gulp
.src(["app/html-dev/fonts/**/*", '!app/html-dev/fonts/empty.woff'])
.pipe(gulp.dest('app/dist/fonts')),
gulp
.src("app/cache/js/**/*")
.pipe(gulp.dest('app/dist/js')),
gulp
.src("app/cache/*.html")
.pipe(gulp.dest('app/dist'))
);
});
The problem you are probably running into is that the tasks aren't necessarily synchronous, so you need to treat them appropriately (i.e., wait for them to complete).
It's probably better to use gulp as it is intended and to have several separate tasks (or ditch gulp entirely and just script something normally). Trying to half use gulp is only going to cause you headaches.
If you are worried about having one massive gulp task list, what you can do instead is group tasks together and then call them.
For example:
gulp.task('html', () => { /* do something */ });
gulp.task('css', () => { /* do something */ });
gulp.task('js', () => { /* do something */ });
gulp.task('clean', () => { /* do something */ });
// Group the build ones into one call
gulp.task('build', ['html', 'css', 'js']);
// Group the default into one
gulp.task('default', ['clean', 'build']);
By grouping them together, you can keep them nice and organized without having to have 100 things in one task. This also lets the benefits of gulp show.

Gulp not concatenating js file in correct order

I am concatenating and minifying js files using gulp. But files are not concatenating in the order it should be, like this is the order I want :
var scriptFiles = [
'assets/lib/js/angular.min.js',
'assets/lib/js/angular-sanitize.min.js',
'assets/lib/js/angular-route.min.js',
'assets/lib/js/angular-ui-router.min.js',
'assets/lib/js/angular-css.min.js',
'assets/lib/js/angular-select.min.js',
'assets/lib/js/duration.js',
'assets/lib/js/ui-codemirror.min.js',
];
The problem is, after concatenation ui-codemirror.min.js file goes to top of the compiled file, which breaks the javascript since angular.js is not initialized/loaded.
To solve this problem I tried to use "gulp-order" package and wrote this gulp task:
gulp.task('lib-js', function() {
return gulp.src(scriptFiles)
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(order(scriptFiles, { base: './' }))
.pipe(concat('vendor.js'))
.pipe(gulp.dest('assets/compiled/js'))
.pipe(rename({ suffix: '.min' }))
.pipe(uglify())
.pipe(gulp.dest('assets/compiled/js'))
});
I passed the same scriptFiles array to try to preserve the order. But it did not work.
Then I tried the streamqueue plugin, and change the task:
gulp.task('lib-js', function() {
return streamqueue({ objectMode: true },
gulp.src('assets/lib/js/angular.min.js'),
gulp.src('assets/lib/js/angular-sanitize.min.js'),
gulp.src('assets/lib/js/angular-route.min.js?v=20161018-1'),
gulp.src('assets/lib/js/angular-ui-router.min.js'),
gulp.src('assets/lib/js/angular-css.min.js'),
gulp.src('assets/lib/js/angular-select.min.js'),
gulp.src('assets/lib/js/jquery-2.1.1.min.js'),
gulp.src('assets/lib/js/material.min.js'),
gulp.src('assets/lib/js/ocLazyLoad.min.js'),
gulp.src('assets/lib/js/duration.js'),
gulp.src('assets/lib/js/ui-codemirror.min.js')
)
.pipe(concat('vendor.js'))
.pipe(gulp.dest('assets/compiled/js'))
.pipe(rename({ suffix: '.min' }))
.pipe(uglify())
.pipe(gulp.dest('assets/compiled/js'))
});
This did not work either. I am unable to debug why this is happening. "order" and "streamqueue" plugin had not effect on the output. Any idea/solution?

Gulp dest: warn if 2 tasks try to write to the same destination

I wonder if there is an easy way to detect if two tasks write to the same file.
In this example there is a /js directory alongside a /ts directory. The /ts will get transpiled to the same directory as the /js. There shouldn't be any collisions. The ask is that, if there are collisions, the ts will win; but, I would like to warn that there is a collision.
gulp.task('js', function() {
return es.concat(
gulp.src(config.src.path('js', '**', '*.js'))
.pipe(gulp.dest(config.build.path(app, 'js')))
//, ....
);
});
gulp.task('ts', ['js'], function() {
var tsResult = gulp.src(config.src.path('ts', '**', '*.ts'))
.pipe(ts({
declaration: true,
noExternalResolve: true
}));
return es.concat([
tsResult.dts.pipe(gulp.dest(
config.build.path(app, 'definitions'))),
tsResult.js.pipe(gulp.dest(
config.build.path(app, 'js'))) // <--- same dest as js task
]);
})
Can I detect that the ts task is overwriting a file that the js task just put in place?
Just an idea. You can pass a callback to gulp.dest like this:
gulp.src('lib/*.js')
.pipe(uglify())
.pipe(gulp.src('styles/*.css'))
.pipe(gulp.dest(function(file) {
if (fs.existsSync('something here')) { // it's a deprecated call, use a newer one
console.warn("File exists", file);
}
// I don't know, you can do something cool here
return 'build/whatever';
}));
The feature is available since Gulp 3.8: https://github.com/gulpjs/gulp/blob/master/CHANGELOG.md#380
Other resources:
https://stackoverflow.com/a/29437418/99256
https://stackoverflow.com/a/29817916/99256

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