詳細検索

Building a CSS/JavaScript Compilation Environment with Gulp ─ CentOS

Avatar
by maeno

Building a CSS/JavaScript Compilation Environment with Gulp ─ CentOS
Translated from 日本語 • View original

Traditionally, CSS and JavaScript, the main assets of the web frontend, were difficult to manage at the source level, and quickly entered chaotic territory and became difficult to maintain. To make CSS and JavaScript in this chaotic area easier to maintain and manage at the source level, the compiled build mechanisms of Grunt and Gulp were created. In today's world, front-end development has become the default development method to improve the efficiency of CSS and JavaScript coding with SCSS (SASS, LESS, etc.), CoffeeScript, etc., while at the same time making it easier to maintain and manage the source. In fact, when I tried CSS styling using variables in LESS and writing JavaScript in CoffeeScript, which has a dramatically low amount of code, I was forced to change the solid front-end coding method I had to change due to the overwhelming high code productivity. ── With that said, I would like to immediately create an environment for compiling and building CSS/JavaScript on a CentOS server for service provision (see this article for introducing CSS/JavaScript to a Windows machine as a local development environment). )。

By the way, Gulp is read as "gulp". I read "group" at first... (Laughter)

Installing Node.js

First of all, Gulp is a node.js module, so it doesn't start without installing node.js. That's why I'm going to install the node.js, but first I'm going to install it from NVM, which is the version control module for node.js and libraries. Clone nvm from GitHub and install it in the included shell, as shown below.

$ git clone git://github.com/creationix/nvm.git ~/.nvm
$ . ~/.nvm/nvm.sh

Next, I install the node.js, but before that, I download the stable version of the current node.js from the official Node.js website. Let's check. It says "Current Version: v0.12.2" in the middle of the TOP page, so it's safe to install that version (the stable version of Node.js as of April 7, 2015 was 0.12.2). Once you have decided on the installation version, install it with NVM.

$ nvm install v0.12.2
$ node -v
v0.12.2

If you check the version and the installation version is displayed, it is OK. Finally, I'd like to add the following statement to the .bashrc so that the node.js is available in my console environment:

$ vim .bashrc
$ cat .bashrc
# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

# User specific aliases and functions

. ~/.nvm/nvm.sh
nvm use v0.12.2
export NODE_PATH=${NVM_PATH}_modules

I'll also check the version of npm installed in the bundle.

$ npm -v
2.7.4

The installation of the Node.js is now complete.

Installing Gulp

Then install Gulp globally.

$ npm install -g gulp
$ glup -v
[**:**:**] CLI version 3.8.11

The installation is now complete. It's easy, isn't it?

Then install it locally. To install locally, npm must be initialized. First, create a directory where you want to run gulp arbitrarily. In this article, I am creating a new directory called '~/gulp_build' in my home directory.

$ mkdir -p gulp_build
$ cd gulp_build
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (gulp_build) gulp_build
version: (1.0.0)
description: Gulp-build-test
entry point: (index.js)
test command:
git repository:
keywords: gulp
author: maeno
license: (ISC) MIT
About to write to /home/maenok/gulp_build/package.json:

{
  "name": "gulp_build",
  "version": "1.0.0",
  "description": "Gulp-build-test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "gulp"
  ],
  "author": "maeno",
  "license": "MIT"
}

Is this ok? (yes) yes

You will be asked for some attribute values interactively, so you can enter them arbitrarily (you can also enter them all). Once initialized, install gulp locally.

$ npm install gulp --save-dev gulp gulp-util
$ gulp -v
[**:**:**] CLI version 3.8.11
[**:**:**] Local version 3.8.11

The '--save-dev' option specifies whether or not to install gulp's development package, so you don't need to add it specifically. Gulp is now available.

Compiling with Gulp

1. Compiling SASS

To compile SASS with qulp, you need a SASS plugin, so install it.

$ npm install gulp-sass --save-dev

Once installed, create the CSS source file from which it compiles.

$ mkdir sass | vi sass/style.scss
$ cat sass/style.scss
a {
    color: #88f;
    &:hover {
        text-decoration: none;
    }
}

Next, create a compilation task. Create a 'gulpfile.js' directly below the directory where you installed gulp locally ('~/gulp_build' in this example).

$ vi ~/gulp_build/gulpfile.js
$ cat ~/gulp_build/gulpfile.js
var gulp = require('gulp');
var gutil = require('gulp-util');
var sass = require('gulp-sass');

gulp.task('sass', function() {
  gulp.src('sass/style.scss')
  .pipe(sass())
  .pipe(gulp.dest('./css'));
});

Once the task is complete, let's run the compilation right away.

$ gulp sass
[**:**:**] Using gulpfile ~/gulp_build/gulpfile.js
[**:**:**] Starting 'sass'...
[**:**:**] Finished 'sass' after 19 ms

You will now have a 'CSS' folder with the compiled CSS files exported in it. If you look inside the CSS file, you can see that

a {
  color: #88f; }
  a:hover {
    text-decoration: none; }

Oh~, it's properly built. Now you have implemented the Gulp + SASS compilation environment. Next, I'm going to try to create a LESS compilation environment.

2. Compiling LESS

Basically, it will flow in the same way as SASS. In other words, you need the LESS plugin to compile LESS with qulp, so install it.

$ npm install gulp-less --save-dev

Once installed, create the CSS source file from which it compiles.

$ mkdir less | vi less/style.less
$ cat less/style.less
@link-color: #88f;

a {
color: @link-color;
&:hover {
text-decoration: none;
}
}

This is an example of using variables for property values in a style that you might find most useful in a CSS precompiled environment.

Then create a compilation task. Edit the 'gulpfile.js' directly below the directory where you installed gulp locally ('~/gulp_build' in this example).

$ vi ~/gulp_build/gulpfile.js
$ cat ~/gulp_build/gulpfile.js
var gulp = require('gulp');
var gutil = require('gulp-util');
var less = require('gulp-less');

gulp.task('less', function() {
  gulp.src('less/**/*.less')
  .pipe(less())
  .pipe(gulp.dest('./css'));
});

Now we have all the '.less' files below 'less/' for the target source. Once you have the task, let's run the compilation right away.

$ gulp less
[**:**:**] Using gulpfile ~/gulp_build/gulpfile.js
[**:**:**] Starting 'less'...
[**:**:**] Finished 'less' after 21 ms

You will now have the compiled CSS file exported inside the 'CSS' folder. If you look inside the CSS file, you can see that

$ cat css/style.css
a {
  color: #8888ff;
}
a:hover {
  text-decoration: none;
}

The LESS compilation is better because the indentation is more formatted than the SASS compilation.

3. Compiling CoffeeScript

The method is almost the same as the aforementioned SASS and LESS, only the plugins used are different. First, install the plugin for compiling CoffeeScript.

$ npm install gulp-coffee --save-dev

Once installed, create the original CoffeeScript file.

$ mkdir coffee | vi coffee/script.coffee
$ cat coffee/script.coffee
Home = ->
  $('.button').on 'click', (e) ->
    e.preventDefault()
    if window.confirm "Are you sure?"
      $(@).trigger 'click'
    else
      return false

$(document).ready(Home)

The sample contains jQuery code. When clicking on the '.button' class element, the event handler will issue a confirmation dialog.

Then create a compilation task. Edit the 'gulpfile.js' directly below the directory where you installed gulp locally ('~/gulp_build' in this example).

var gulp = require('gulp');
var gutil = require('gulp-util');
var coffee = require('gulp-coffee');

gulp.task('coffee', function() {
  gulp.src('coffee/**/*.coffee')
  .pipe(coffee())
  .pipe(gulp.dest('./js'));
});

The target source will be all '.coffee' files below 'coffee/'. Let's run the compilation right away.

$ gulp coffee
[**:**:**] Using gulpfile ~/gulp_build/gulpfile.js
[**:**:**] Starting 'coffee'...
[**:**:**] Finished 'coffee' after 26 ms

You now have a 'js' folder and the compiled JavaScript file is exported to it. If you look inside the JavaScript file, you can see that

(function() {
  var Home;

Home = function() {
    return $('.button').on('click', function(e) {
      e.preventDefault();
      if (window.confirm("Are you sure?")) {
        return $(this).trigger('click');
      } else {
        return false;
      }
    });
  };

$(document).ready(Home);

}).call(this);

Great!

By the way, Gulp's plugins can coexist with each other, so you can merge each task into a 'gulpfile.js' to create an environment where you can compile SASS, LESS, and CoffeeScript. There are also quite a few other valid ones in Gulp plugins that should be defined by default (such as automatic vendor prefix granting and minifying), so it's a good idea to look for them according to your usage scenario.

With this, we have a modern web service environment in which CSS and JavaScript are managed and developed on GitHub and other platforms, while the source is precompiled and deployed on the service environment side such as CentOS servers.

Related Articles