How to add .watch to gulpfile.js - node.js

I am using gulp for minify JS and CSS.
Everything works fine, but I need add .watch for automatic this process.
Anyone help me please?
Here is my code:
// Require the npm modules we need
var gulp = require("gulp"),
rename = require("gulp-rename"),
cleanCSS = require("gulp-clean-css"),
terser = require("gulp-terser");
// Looks for a file called styles.css inside the css directory
// Copies and renames the file to styles.min.css
// Minifies the CSS
// Saves the new file inside the css directory
function minifyCSS() {
return gulp.src("./_statika/css/style.css")
.pipe(rename("style.min.css"))
.pipe(cleanCSS())
.pipe(gulp.dest("./css"));
}
// Looks for a file called app.js inside the js directory
// Copies and renames the file to app.min.js
// Minifies the JS
// Saves the new file inside the js directory
function minifyJS() {
return gulp.src("./_statika/js/scripts.js")
.pipe(rename("scripts.min.js"))
.pipe(terser())
.pipe(gulp.dest("./js"));
}
// Makes both functions available as a single default task
// The two functions will execute asynchronously (in parallel)
// The task will run when you use the gulp command in the terminal
exports.default = gulp.parallel(minifyCSS, minifyJS);
Thanks a lot

Just try this:
gulp.watch("./_statika/css/style.css", minifyCSS);
gulp.watch("./_statika/js/scripts.js", minifyJS);

Related

Accessing development folder as if it is node global folder

I've modules folder which contains my modules for app1 and have another module folder for app2 and so on.
I wish to import my modules without passing virtual module paths.
For eg.
c:\Projects\Apps\
firstApp
www.js // I wish to import db with require('db')
Modules
db
src/...*.js // var ext=require('extensions')
test/...*.js
index.js
api
src/
*.js // var ext=require('db'),
// var ext=require('extensions'),
test/
*.js // var testApi = require('api')
index.js
extensions
src/...*.js
test/...*.js
index.js
Is there any possibilities to use them as if they are installed localy but in different folders. npm link is usable for this?
require('...') will look for modules inside node_modules folder or local files when using ./ or ../.
What you can do is create your own require function that will look for local files even when not using relative/absolute file paths.
In your root/entry code, use this:
var projectDirectory = __dirname;
GLOBAL.requirep = function(path) {
return require(projectDirectory + '/' + path);
}
//at any js file, you can do this:
var db = requirep('db') //will load db/index.js
var api = requirep('api/src/file.js') //will load api/src/file.js
Because it is global, you can access it from wherever you need.

pre-load / pre-require directories of .js route files

Using Express with Node.js, we might do something like this:
app.use('api/:controller/:action/:id', function(req,res,next){
var controller = req.params.controller;
var action = req.params.action;
var route = require('./routes/' + controller + '/' + action);
route(req,res,next);
}
now this is all fine and well, except there is at least one problem: the route file is dynamically loaded at runtime if this file has not been 'require'd yet. Which means it's a little bit slower at least.
Does someone have a script that recurses through a directory and pre-loads/pre-requires all the .js files when a server first starts up?
I have a similar problem for the front-end as well, using RequireJS. The solution seems to be to write a bash script that writes out all the .js filepaths in a directory and its subdirectories to a text file. then when the server starts up, it reads that text file and requires all the files in the directory that are listed in the text file. Is that the best way to do it?
If you can use io.js, it can preload modules using command-line -r or --require:
iojs -r <module_name> server.js
I created an NPM module that does this for the front-end, doing it for Node.js / CommonJS is another story.
https://www.npmjs.com/package/requirejs-metagen
you can use it like so:
var grm = require('requirejs-metagen'); //you can use with Gulp
var controllersOpts = {
inputFolder: './public/static/app/js/controllers/all',
appendThisToDependencies: 'app/js/controllers/',
appendThisToReturnedItems: '',
eliminateSharedFolder: true,
output: './public/static/app/js/meta/allControllers.js'
};
grm(controllersOpts,function(err){
//handle errors your own way
});
it generates a corresponding AMD/RequireJS module like so:
define(
[
"app/js/controllers/all/jobs",
"app/js/controllers/all/users"
],
function(){
return {
"jobs": arguments[0],
"users": arguments[1]
}
});
you can also require subdirectories and all that stuff like so:
var allViewsOpts = {
inputFolder: './public/static/app/js/jsx',
appendThisToDependencies: 'app/js/',
appendThisToReturnedItems: '',
eliminateSharedFolder: true,
output: './public/static/app/js/meta/allViews.js'
}
grm(allViewsOpts );
which generates output like so:
define([
"app/js/jsx/BaseView",
"app/js/jsx/reactComponents/FluxCart",
"app/js/jsx/reactComponents/FluxCartApp",
"app/js/jsx/reactComponents/FluxProduct",
"app/js/jsx/reactComponents/Item",
"app/js/jsx/reactComponents/Job",
"app/js/jsx/reactComponents/JobsList",
"app/js/jsx/reactComponents/listView",
"app/js/jsx/reactComponents/Picture",
"app/js/jsx/reactComponents/PictureList",
"app/js/jsx/reactComponents/RealTimeSearchView",
"app/js/jsx/reactComponents/Service",
"app/js/jsx/reactComponents/ServiceChooser",
"app/js/jsx/reactComponents/todoList",
"app/js/jsx/relViews/getAll/getAll",
"app/js/jsx/relViews/jobs/jobsView",
"app/js/jsx/standardViews/dashboardView",
"app/js/jsx/standardViews/overviewView",
"app/js/jsx/standardViews/pictureView",
"app/js/jsx/standardViews/portalView",
"app/js/jsx/standardViews/registeredUsersView",
"app/js/jsx/standardViews/userProfileView"
],
function(){
return {
"BaseView": arguments[0],
"reactComponents/FluxCart": arguments[1],
"reactComponents/FluxCartApp": arguments[2],
"reactComponents/FluxProduct": arguments[3],
"reactComponents/Item": arguments[4],
"reactComponents/Job": arguments[5],
"reactComponents/JobsList": arguments[6],
"reactComponents/listView": arguments[7],
"reactComponents/Picture": arguments[9],
"reactComponents/PictureList": arguments[10],
"reactComponents/RealTimeSearchView": arguments[11],
"reactComponents/Service": arguments[12],
"reactComponents/ServiceChooser": arguments[13],
"relViews/getAll/getAll": arguments[14],
"relViews/jobs/jobsView": arguments[15],
"standardViews/dashboardView": arguments[16],
"standardViews/overviewView": arguments[17],
"standardViews/pictureView": arguments[18],
"standardViews/portalView": arguments[19],
"standardViews/registeredUsersView": arguments[20],
"standardViews/userProfileView": arguments[21]
}
});
I need to update the library so it returns the stream so you can handle when it completes, otherwise it works great.

How can get the file directory that require my npm packages

I created a npm package. In the function,I need to know whice file require my package. How can I do ?
sample:
this is my package.json
{
name: "path-judge",
main: "lib/index.js"
}
exports.doSomething = function(){
//how can I get the file path that require this package.
//....
}
if there is a file test.js require path-judge, like this:
var judge = require("path-judge");
judge.doSomething();
in the index.js how can I get the test.js file path?
the test.js isn't the main function, other file require it.
for example:
node other.js
other.js:
test = require '../../test.js'
//...
console.log('....')
You can check module.parent. If that property exists, then it means the module is being loaded via require() and not node mymodule.js directly.
In this object is a filename property. So you can easily use path.dirname() on this value to extract the directory portion to get the path to the script doing the require(). Example:
var path = require('path');
if (module.parent) {
console.log(path.dirname(module.parent.filename));
}

How to rename all files in a folder using gulp js?

I have a bunch of html files in a partials directory. Using gulp js, I want to minify and rename these files to .min.html. Please show me how to achieve this.
See here, using gulp-rename, if you just want to rename the files.
Something in the line of below should do:
var rename = require('gulp-rename');
gulp.src("./partials/**/*.hmtl")
.pipe(rename(function (path) {
path.suffix += ".min";
}))
.pipe(gulp.dest("./dist"));
In order to minify, you can use gulp-htmlmin. Pretty straightforward from the documentation:
var htmlmin = require('gulp-htmlmin');
gulp.task('compress', function() {
gulp.src('./partials/**/*.html')
.pipe(htmlmin())
.pipe(gulp.dest('dist'))
});
You can certainly combine the two to obtain the desired effect.

How to use jasmine with gulp.watch

I'm trying to make my tests run each time I'm saving some files. Here is the gulp watch:
gulp.task('jasmine', function() {
gulp.src('spec/nodejs/*Spec.js')
.pipe(jasmine({verbose:true, includeStackTrace: true}));
});
gulp.task('watch', function () {
gulp.watch(['app/*.js', 'app/!(embed)**/*.js','spec/nodejs/*.js'], ['jasmine']);
});
To test for example app/maps.js I'm creating a spec/nodejs/mapsSpec.js file like this:
'use strict';
var maps = require('../../app/maps');
describe('/maps related routes', function(){
it('should ...', function(){...}
...
If I change a spec file everything is working well, if I modify app/maps.js file the change trigger the test. if I modify it again tests are tiggered but the modifications do not taking effect. For example if I add a console.log('foo') in a second time, I will not see it until I relaunch gulp watch and save it again. So only one run of jasmine is ok when using it with gulp.watch.
I guess it's because require is cached by nodejs in the gulp process. So how should I do ?
I took a look at the code of gulp-jasmine. The problem is that the only file from the cache is the Specs.js file. The cache of the children(the reqquired files to test) aren't cleared.
Within the index.js of gulp-jasmine is a row which deletes the cache:
delete require.cache[require.resolve(path.resolve(file.path))];
If you put the next block of code before the delete, you will delete all the children's cache and will it run correctly after every time you save your file.
var files = require.cache[require.resolve(path.resolve(file.path))];
if( typeof files !== 'undefined' ) {
for( var i in files.children ) {
delete require.cache[ files.children[i].id ];
}
}
You can change this in the node_modules.
I will go for a pull request, so maybe in the near future this will be solved permanently.
Also wrote a post about it on: http://navelpluisje.nl/entry/fix-cache-problem-jasmine-tests-with-gulp
I haven't found a fix for this issue, but you can work around it via the gulp-shell task.
npm install gulp-shell --save-dev
then
var shell = require('gulp-shell');
...
gulp.task('jasmine', function() {
gulp.src('spec/nodejs/*Spec.js')
.pipe(shell('minijasminenode spec/*Spec.js'));
});
You'll also need jasmine installed as a direct dependency (gulp-jasmine uses minijasminenode)

Resources