9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Gulpを使ってsassを自動コンパイル&ブラウザリロード&JS,CSS圧縮(備忘録)

Last updated at Posted at 2017-01-10

※Node.jsとGulpがインストールされている前提

ディレクトリ構成は下記の通り

├── css
├── js
    ├── jquery
        ├── **.js
├── sass
    ├── header
        ├── **.scss
    |
|   ├── **.scss
|   └── **.scss
├── index.html

ターミナル、コマンドプロンプトで作業ディレクトリまで移動して、下記コマンドを入力していく

npm init
npm install gulp --save-dev
npm install gulp-sass --save-dev
npm install --save-dev gulp-sourcemaps
npm install --save-dev gulp-plumber
npm install browser-sync
npm install gulp-uglify --save-dev
npm install gulp-clean-css --save-dev
gulpfile.js
const gulp        = require('gulp');
const sass        = require('gulp-sass');
const plumber     = require('gulp-plumber');
const sourcemaps  = require('gulp-sourcemaps');
const browserSync = require('browser-sync');
const uglify      = require('gulp-uglify');
const cleanCSS    = require('gulp-clean-css');

// sassコンパイルタスク
gulp.task('sass', function(){
  gulp.src('./scss/**/*.scss')
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./css/'));
});

// ブラウザリロード
gulp.task('browser-sync', function() {
    browserSync({
        server: {
             baseDir: "."       //対象ディレクトリ
            ,index  : "000_top.html"      //インデックスファイル
        }
    });
});
gulp.task('bs-reload', function () {
    browserSync.reload();
});

//JS圧縮
gulp.task('minify-js', function() {
    return gulp.src("./js/**/*.js")
        .pipe(uglify())
        .pipe(gulp.dest('./dist/js/')); //別ディレクトリ
        //.pipe(gulp.dest('./js')); // overwrite
});

//CSS圧縮
gulp.task('minify-css', function() {
    return gulp.src("./css/*.css")
        .pipe(cleanCSS())
        //.pipe(gulp.dest('./dist/css/')); //別ディレクトリ
        .pipe(gulp.dest('./css')); // overwrite
});

// watchタスク(html,js,sassファイル変更時に実行するタスク)
gulp.task('sass-watch', ['sass','browser-sync'], function(){
  let watcher = gulp.watch('./scss/**/*.scss', ['sass']);
  gulp.watch("./*.html",['bs-reload']);
  watcher.on('change', function(event) {
    console.log('コンパイルOK!');
  });
  gulp.watch("./scss/**/*.scss",['bs-reload']);
  gulp.watch("./js/**/*.js",['bs-reload']);
});

gulp.task('default', ['sass-watch','browser-sync']);
gulp.task('build',['minify-css','minify-js']);

gulp

を入力して、実行

gulp build

を入力して、JS,CSS圧縮を実行

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?