Professional Documents
Culture Documents
JS
¿QUÉ ES GULP.JS?
Es un build system(sistema de construcción) que permite automatizar
tareas comunes de desarrollo, tales como la minificación de código
JavaScript, recarga del navegador, compresión de imágenes, validación
de sintaxis de código y un sin fin de tareas más.
Si hoy en día no quieres perder tiempo realizando tareas comunes
“manualmente”, es momento de que aprendas a usar un automatizador
como Gulp.js.
Gulp.js está construído con Javascript, funciona sobre Node.js y es Open
Source,
Gulp.js utiliza el método pipe(), este método obtiene todos los datos de
un Stream legible(readable) y lo escribe en el destino que le indiquemos
ó de lo contrario lo entrega o sirve hacia otro pipe.
Gulp.js utiliza el poder del paquete Node.js vinyl-fs para leer y escribir
Streams.
3. Si todo ha ido bien, ahora nos toca instalar gulp de manera global, esto
lo haremos una sola vez en nuestro equipo. Si queremos asegurarnos si
ya tenemos instalado gulp, escribimos el comando:
Y nos ira pidiendo que ingresemos información, para saltarte los datos que no desees
llenar pulsa la tecla Enter
En caso no deseamos ingresar información usaremos el siguiente comando: npm init –y
Gulp.js tiene una pequeña API, esto te permitirá aprender Gulp.js rápidamente
Para llamar esta tarea tan solo escribimos en nuestra terminal: gulp
demo
Una tarea también puede actuar como una lista de tareas,
supongamos que queremos definir una tarea que corra otras 3
tareas por ejemplo: imágenes, css y js. Entonces escribiríamos lo
siguiente:
Y claro, también puedes hacer que tu tarea por defecto sea una lista
de tareas, así:
Esta tarea ejecutará las tarea ‘css’ y ‘js’, tan solo escribiendo en
nuestra terminal:
GULP.SRC()toma como parámetro un valor glob es decir, una cadena que
coincida con uno o más archivos usando los patrones que usa el
intérprete de comandos de unix(shell) y retorna un stream que puede ser
“pipeado” a un plugin adicional ó hacia el método gulp.dest().
Ejemplos de glob:
Cada vez que Gulp.js encuentre un archivo que coincida con nuestro
patrón, lo irá metiendo dentro de un Stream, que será como una
colección de archivos. Claro, respetando las propiedades de cada
archivo(ruta, etc).
Entonces podemos decir que tendremos todos esos archivos con sus
respectivas propiedades dentro de un Stream, Este Stream puede ser
manipulado por Gulp.js.
El método pipe() puede leer, ayudar a transformar y grabar los datos de
un Stream.
gulp uglify
3. Renombrar Archivos
Ejecutamos la tarea con gulp
El resultado es
Ver https://www.npmjs.com/package/gulp-rename
gulp.task('default', function() {
runSequence(
['minify-css', 'minify-js'], // estas dos corren en
paralelo de primero
);
});
https://www.npmjs.com/package/run-sequence
8. Concatenar y minificar js
Ejemplo
Finalmente añadimos la opción drop_console en el plugin uglify para quitar los
comentarios y aprovechamos para introducir un watcher que ejecute la tarea
minify y añadimos la dependencia del watcher en la tarea por defecto. De esta
manera cuando ejecutemos la tarea gulp se ejecutará el watcher y cuando se
modifique algún fichero del código fuente se aplicará la tarea de minificación.
gulp.task('minify', function() {
console.log('minifying js ...');
return gulp.src('src/js/*.js')
.pipe(concat('all.js'))
.pipe(uglify({
compress: {
drop_console: true
}
}))
.pipe(gulp.dest('build/js/'));
});
gulp.task('watch-js', function() {
gulp.watch('src/js/*.js', ['minify'], function() {
console.log('watching js changes...');
});
});
We've now managed to compile all Sass files into CSS files with a single command. The
question is, what good does it do if we have to run gulp sass manually every time we
want to compile Sass into CSS?
Luckily, we can tell Gulp to automatically run the sass task whenever a file is saved
through a process called "watching".
Gulp provides us with a watch method that checks to see if a file was saved. The
syntax for the watch method is:
If we want to watch all Sass files and run the sass task whenever a Sass file is saved,
we just have to replace files-to-watch with the app/scss/**/*.scss,
and ['tasks', 'to', 'run'] with ['sass']:
More often though, we'll want to watch more than one type of file at once. To do so,
we can group together multiple watch processes into a watchtask:
gulp.task('watch', function(){
gulp.watch('app/scss/**/*.scss', ['sass']);
// Other watchers
})
If you ran the gulp watch command right now, you'll see that Gulp starts watching
immediately.
And that it automatically runs the sass task whenever you save a .scss file.
Let's take it a step further and make Gulp reload the browser whenever we save
a .scss file with the help of Browser Sync.
Browser Sync helps make web development easier by spinning up a web server that
helps us do live-reloading easily. It has other features, like synchronizing actions across
multiple devices, as well.
We'll first have to install Browser Sync:
You may have noticed that there isn't a gulp- prefix when we install Browser Sync.
This is because Browser Sync works with Gulp, so we don't have to use a plugin.
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: 'app'
},
})
})
We also have to change our sass task slightly so Browser Sync can inject new CSS
styles (update the CSS) into the browser whenever the sasstask is ran.
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.scss') // Gets all files ending
with .scss in app/scss
.pipe(sass())
.pipe(gulp.dest('app/css'))
.pipe(browserSync.reload({
stream: true
}))
});
We're done with configuring Browser Sync. Now, we have to run both
the watch and browserSync tasks at the same time for live-reloading to occur.
It'll be cumbersome to open up two command line windows and run gulp
browserSync and gulp watch separately, so let's get Gulp to run them together by
telling the watch task that browserSync must be completed before watch is allowed
to run.
We can do so by adding a second argument to the watch task. The syntax is:
// ...
})
gulp.task('build', [`clean`, `sass`, `useref`, `images`, `fonts`],
function (){
console.log('Building files');
})
Unfortunately, we wouldn't be able to write the build task this way because Gulp
activates all tasks in the second argument simultaneously.
So, to ensure that cleans get completed before the rest of the tasks, we need to use an
extra plugin called Run Sequence.
gulp.task('task-name', function(callback) {
});
In this case, Gulp first runs task-one. When task-one is completed, Gulp runs every
task in the second argument simultaneously. All tasks in this second argument must be
completed before task-three is run.
So we can now create a task that ensures that clean:dist runs first, followed by all
the other tasks:
runSequence('clean:dist',
callback
})
To make things consistent, we can also build the same sequence with the first group.
Let's use default as the task name this time:
Why default? Because when you have a task named default, you can run it simply
by typing the gulp command, which saves some keystrokes.
Finally, here's a github repo for all the work we've done!
#Wrapping it up
We've gone through the absolute basics of Gulp and created a workflow that's able to
compile Sass into CSS while watching HTML and JS files for changes at the same time.
We can run this task with the gulp command in the command line.
We've also built a second task, build, that creates a dist folder for the production
website. We compiled Sass into CSS, optimized all our assets, and copied the necessary
folders into the dist folder. To run this task, we just have to type gulp build into the
command line.
Lastly, we have a clean task that clears away from the generated distfolder any
image caches that are created, allowing us to remove any old files that were
inadvertently kept in dist.
We've created a robust workflow so far that's capable enough for most web
developers. There's a lot more to Gulp and workflows that we can explore to make this
process even better. Here are some ideas for you:
For development:
For optimization:
As you can see, even though the workflow we've created does quite a few things,
there's a lot more that can be done. Creating a workflow that suits your needs can be
extremely exciting and fulfilling, but it can be a lot to take in if you're new to this.
There's so much more to Gulp that it's impossible to cover within this blog post, or
even a series of posts. That's why I wrote a book on automating your workflow, and I
invite you to grab ten chapters for free if you're interested in finding out more :)
Let me know what you felt about this article in the comments below! Oh yes, feel free
to contact me if you have any questions on workflow. I'll be happy to reply!
11. Ejemplo
Copyright
/*
Gulp Examples by @julienrenaux:
* https://github.com/shprink
* https://twitter.com/julienrenaux
* https://www.facebook.com/julienrenauxblog
*/
// including plugins
, fs = require('fs')
, concat = require("gulp-concat")
, header = require("gulp-header");
// functions
return fs.readFileSync('Copyright');
};
// task
gulp.task('concat-copyright', function () {
.pipe(header(getCopyright()))
.pipe(gulp.dest('path/to/destination'));
});
gulp concat-copyright
// task
gulp.task('concat-copyright-version', function () {
gulp.src('./JavaScript/*.js')
.pipe(concat('concat-copyright-version.js')) // concat and name it
"concat-copyright-version.js"
.pipe(header(getCopyrightVersion(), {version: getVersion()}))
.pipe(gulp.dest('path/to/destination'));
});
Copyright
/*
* https://github.com/shprink
* https://twitter.com/julienrenaux
* https://www.facebook.com/julienrenauxblog
*/
Version
1.0.0
gulpfile.js:
// including plugins
, fs = require('fs')
, coffeelint = require("gulp-coffeelint")
, coffee = require("gulp-coffee")
, uglify = require("gulp-uglify")
, concat = require("gulp-concat")
, header = require("gulp-header");
// functions
return fs.readFileSync('Version');
};
return fs.readFileSync('Copyright');
};
// task
gulp.task('bundle-one', function () {
.pipe(gulp.dest('path/to/destination'));
});
Run:
gulp bundle-one
Tasks automation
Using gulp.watch you can easily automate any tasks when files are
modified. It is really convenient because you do not have to run single
tasks by hand every time a file is modified, and therefore your code is
always up to date.
// including plugins
var gulp = require('gulp');
// task
gulp.task('watch-coffeescript', function () {
gulp.watch(['./CoffeeScript/*.coffee'], ['compile-coffee']);
});
Run:
Now run the task:
gulp watch-coffeescript
and see what happens when you modify one of the source file.
13.
gulp.task('sass', function () {
});
gulp.task('watch', function(){
gulp.watch('./sass/**/*', ['sass']);
});
gulp.task('comprimir-css', function() {
gulp.task('watch', function(){
gulp.watch('./css/**/*', ['comprimir-css']);
});
gulp.task('default',['watch', 'comprimir-css']);
Comprimir archivos JS
Crea una carpeta con el nombre js en el proyecto gulp.
pump([
],
cb
);
});
gulp.task('watch', function(){
gulp.watch('./js/**/*', ['compress-js']);
});
Comprimir Imágenes
Para poder ayudar en la carga de nuestra página web al momento de ser
renderizado en el navegador es aconsejable comprimir las imágenes
para producción.
Pero realizar esta tarea puede ser engorrosa o hasta aburrida, pero
gracias a Gulpesta tarea es mas fácil.
gulp.src('./images/**/*.{png,jpg,jpeg,gif,svg}')//Ruta a la carpeta
images a puntando a las imágenes
.pipe(imagemin({
progressive: true,
use: [pngcrush()]
}))
});
gulp.task('watch', function(){
gulp.watch('./images/**/*', ['images']);
});
gulp.task('default',['watch', 'images']);
Unir ó Concatenar archivos CSS y JS
Muchas veces trabajamos con múltiples archivos pero no los unimos en
un solo archivo, porque es mas cómodo trabajarlo por separado.
gulp.task('unir-files', function() {
.pipe(gulp.dest('./dist/')) //Destino
});
gulp.task('watch', function(){
gulp.watch('./css/**/*', ['unir-files']);
});
gulp.task('default',['watch', 'unir-files']);
//Tareas por defecto
14. Ejemplo
15. Ejemplo
16. Ejemplo
miproyecto Si
ves esta pantalla, quiere decir que el proyecto se ha compilado de
manera exitosa. Si ahora vamos a
la ubicación C:\Miproyecto\js\build, encontraremos un archivo
llamado compilacion.js y al abrirlo tendrá este aspecto: Gulp.js nos
facilitará la vida permitiéndonos optimizar distintos procesos. No
importa si eres desarrollador Front-end o Backend, Gulp.js es una
herramienta que te ahorrará muchos problemas a la hora de crear
un proyecto web.
// Lets add a custom env var. Good for injecting AWS_RDS config variables.
collection.env = Object.assign({
MY_CUSTOM_ENV_VAR: "env_var_value"
}, process.env);
return collection;
} else if (type === connect.OPTIONS_PHP_CLI_ARR) { // As the constant suggests, collection is an Arr
ay.
let newArgs = [
'-e', // Generate extended information for debugger/profiler.
'-d', 'memory_limit=2G' // Define INI entry, Up memory limit to 2G.
];
// Ensure our argument switches appear before the rest.
return newArgs.concat(collection);
}
}
}, function _connected_callback() {
console.log("PHP Development Server Connected.");
});
});
gulp.task('disconnect', function() {
connect.closeServer();
});
There's no official Browsersync plugin for Gulp, because it's not needed! You
simply require the module, utilise the API and configure it with options. The
following are some common use-cases as seen in popular projects such
as Google's web starter kit and many others.
Install^ TOP
// Static server
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "./"
}
});
});
// or...
gulp.task('browser-sync', function() {
browserSync.init({
proxy: "yourlocal.dev"
});
});
Streams are supported in Browsersync, so you can call reload at specific points
during your tasks and all browsers will be informed of the changes. Because
Browsersync only cares about your CSS when it's finished compiling - make sure
you call .stream() after gulp.dest
browserSync.init({
server: "./app"
});
gulp.watch("app/scss/*.scss", ['sass']);
gulp.watch("app/*.html").on('change', browserSync.reload);
});
gulp.task('default', ['serve']);
Sometimes you might just want to reload the page completely (for example, after
processing a bunch of JS files), but you want the reload to happen after your tasks.
This will be easier in gulp 4.x.x , but for now you can do the following (make sure
you return the stream from your tasks to ensure that browserSync.reload() is
called at the correct time).
If you are using gulp 4.x.x now, then you can follow this documentation.
If the streams support doesn't suit your needs, you can fire the reload method
manually by wrapping it in a task. This example will compile & auto-inject CSS just
as before, but when HTML files are changed, the browsers will be reloaded
instead.
// Watch scss AND html files, doing different things with each.
gulp.task('serve', function () {
gulp.watch("*.html").on("change", reload);
});
21. Ejemplo
The end result will be a pretty sweet front-end development setup including:
##Prerequisites
##Assumptions
We need to install 3 tools locally to our project - gulp, gulp-sass & browser-sync. In
your terminal/command line, navigate to your project directory and run
Open up gulpfile.js in your favourite editing tool and place this at the top.
We'll have a separate task for compiling SCSS into CSS & one for starting
BrowserSync.
SASS - Here we specify the path to our main scss file (the one that contains all of
the @imports), then we pipe the files into the sass function (that we required
above) and finally into gulp.dest which will write the output into the CSS directory.
gulp.task('sass', function () {
gulp.src('scss/styles.scss')
.pipe(sass({includePaths: ['scss']}))
.pipe(gulp.dest('css'));
});
BrowserSync - First we tell BrowserSync to watch any css & js files for changes
(which will allow the live updating/reload features to work) & the second param
can contain any normal BrowserSync options. In our case though, we just want to
start a server in the root of the project.
gulp.task('browser-sync', function() {
browserSync.init(["css/*.css", "js/*.js"], {
server: {
baseDir: "./"
}
});
});
Watch - So far we've configured two separate tasks & now we'll tie them together
using gulp's default task. First, we will run the sass compiler ONCE (to ensure the
first page load has the latest CSS) & then BrowserSync will start the server & open
up a browser. Finally we watch the scss files in the background for changes & run
the sass task each time.
gulp.task('sass', function () {
gulp.src('scss/styles.scss')
.pipe(sass({includePaths: ['scss']}))
.pipe(gulp.dest('css'));
});
gulp.task('browser-sync', function() {
browserSync.init(["css/*.css", "js/*.js"], {
server: {
baseDir: "./"
}
});
});
We're all set up now. All that remains is to head back to the command-line and run.
gulp
A browser window will open up automatically & will serve up your index.html file.
Take note of the URL, you can use it on any device that's connected to your WIFI
network & all of the BrowserSync features will work across them all. (create for
reponsive stuff).
Don't forget, you're being watched - you now have a great development
workflow where any changes to scss files will automatically trigger the compilation.
When that's done, BrowserSync will notice that the css file was changed & will
auto-inject the new file into all browsers.
##Notes
/**
* This example:
* Uses the built-in BrowserSync server for HTML files
* Watches & compiles SASS files
* Watches & injects CSS files
*
* More details: http://www.browsersync.io/docs/gulp/
*
* Install:
* npm install browser-sync gulp gulp-sass --save-dev
*
* Then run it with:
* gulp
*/
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gulp = require('gulp');
var sass = require('gulp-sass');
// Sass task, will run when any SCSS files change & BrowserSync
// will auto-update browsers
gulp.task('sass', function () {
return gulp.src('scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('css'))
.pipe(reload({stream:true}));
});
var paths = {
css: 'assets/sass/**/*.scss',
php: '**/*.php'
};
gulp.task('connect-sync', function() {
return connect.server({}, function (){
browserSync({
proxy: 'localhost:8000'
});
});
});
gulp.task('css', function() {
return gulp.src(paths.css)
.pipe(sass({
outputStyle: 'expanded',
indentWidth: 4
})
.on('error', sass.logError))
.pipe(postcss([ autoprefixer({
browsers: ['last 2 versions']
}) ]))
.pipe(gulp.dest('assets/css/'))
});
gulp.task('watch', function() {
gulp.watch(paths.php).on('change', browserSync.reload);
gulp.watch(paths.css, ['css']).on('change',
browserSync.reload);
});
(Estoy usando una Mac con versión Gulp: 3.9.1.) Todo funciona
bien a excepción de la recarga del navegador. ¿Alguna idea sobre
cómo solucionarlo?
gulp.task('serve', function() {
browserSync(config.browserSync);
watch(config.styles.sass.src, function() {
gulp.start('assets:styles');
});
watch(config.assets.scripts.watch, function() {
gulp.start('assets:scripts');
});
...
});
browserSync: {
proxy: localhost:8000,
notify: false,
files: [dest + '/**/*']
24. Ejemplo
25. gulp.task('php-serve', ['styles', 'fonts'], function () {
26. connect.server({
27. port: 9001,
28. base: 'app',
29. open: false
30. });
31.
32. var proxy = httpProxy.createProxyServer({});
33.
34. browserSync({
35. notify: false,
36. port : 9000,
37. server: {
38. baseDir : ['.tmp', 'app'],
39. routes : {
40. '/bower_components': 'bower_components'
41. },
42. middleware: function (req, res, next) {
43. var url = req.url;
44.
45. if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
46. proxy.web(req, res, { target: 'http://127.0.0.1:9001' });
47. } else {
48. next();
49. }
50. }
51. }
52. });
53.
54. // watch for changes
55. gulp.watch([
56. 'app/*.html',
57. 'app/*.php',
58. 'app/scripts/**/*.js',
59. 'app/images/**/*',
60. '.tmp/fonts/**/*'
61. ]).on('change', reload);
62.
63. gulp.watch('app/styles/**/*.scss', ['styles']);
64. gulp.watch('app/fonts/**/*', ['fonts']);
65. gulp.watch('bower.json', ['wiredep', 'fonts']);
66. });
67. Ejemplo
68. Asdsad
69. Sadsad
70. Asda
71. Sdasd
72. asdsad