[NodeJS] Gulp with plugins 前端完整解決方案教學

Gulp基本安裝

  1. 安裝NodeJS至目前OS上,將使用NodeJS的NPM管理套件(Command Line)

    查看版本:node -v , npm -v

  2. 先在全域(Global)安裝Gulp:

    npm install -g gulp

    Gulp.js on Github

  3. 進入到專案資料夾,進行NPM專案初始化:

    npm init

    主要目的是建立package.json,以便繼續安裝Packages。

  4. 進入到專案資料夾,進行Package安裝(Dev Mode):

    npm install gulp --save-dev

    查看版本: gulp --version

  5. 建立gulpfile.js於專案資料夾:

    var gulp = require('gulp');
    
    gulp.task('hello', function(){
    console.log('Hello Gulp.js');
    });

    使用指令 gulp hello 來確認Gulp是否正確執行hello任務


Plugins安裝

選用列表

Plugin Description
Gulp Webserver Web server
Gulp SASS SASS/SCSS 編譯器
Gulp FileIclude 如想使用Include方式可用,否則建議使用Gulp HTML Extend
Gulp HTML Extend Layout工具,可取代Gulp FileIclude
Gulp Debug Pipe Debug工具,用來識別檔案
Gulp Rename 重新命名檔名(For min file)
Gulp Clean CSS Minify CSS
Gulp Uglify Minify/Uglify JS

整合TASKS

// Requirement
var gulp = require('gulp');
var webserver = require('gulp-webserver');
var sass = require('gulp-sass');
var fileinclude = require('gulp-file-include');

// Dist path
var distPath = './app';
var distAssetPath = distPath + '/assets';

// Combined task for Web Dev
gulp.task('default', [
    'webserver',
    'assets-deploy',
    'assets-deploy:watch',
    'sass',
    'sass:watch',
    'fileinclude',
    'fileinclude:watch',
]);

//  gulp-webserver
gulp.task('webserver', function() {
    gulp.src(distPath)
        .pipe(webserver({
            livereload: true,
            directoryListing: false,
            open: true
        }));
});

// Deploy Assets
var assetSource = './assets/**/*';
gulp.task('assets-deploy', function() {
    gulp.src([assetSource])
        .pipe(gulp.dest(distAssetPath));
});
gulp.task('assets-deploy:watch', function() {
    gulp.watch(assetSource, ['assets-deploy']);
});

// gulp-sass
var sassSource = './sass/**/*.scss';
var cssPath = distAssetPath + '/css';
gulp.task('sass', function() {
    return gulp.src(sassSource)
        .pipe(sass.sync().on('error', sass.logError))
        .pipe(gulp.dest(cssPath));
});
gulp.task('sass:watch', function() {
    gulp.watch(sassSource, ['sass']);
});

// gulp-file-include
var viewPath = './views/**/*.html';
gulp.task('fileinclude', function() {
    gulp.src([viewPath])
        .pipe(debug())
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(gulp.dest(distPath));
});
gulp.task('fileinclude:watch', function() {
    gulp.watch(viewPath, ['fileinclude']);
});

Git 協同方式

package.json 相依套件

安裝公用套件使用--save-dev參數即會在package.json加入devDependencies

GitIgnore Node Modules

在Git中忽略node_modules資料夾,公用模組統一每個開發者自行補齊。.gitignore:

# Node Modules
/node_modules

Clone & Pull

起始或更新專案時,公用模組node_modules透過在專案資料夾下的安裝指令更新:

npm install

Leave a Reply

Your email address will not be published. Required fields are marked *