かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

Gulp ディレクトリ構造を保ったままリネームしたい

ニッチ過ぎて一体どこに需要があるのか謎すぎるのですが、gulpでディレクトリ構造を保ったままリネームして出力する方法を試していたのでメモです。
stylusで試してますがpugやsass、jsファイルでも同じかと思います。

renameしない場合、パスの/**/の部分のディレクトリは出力される

// gulpfile.js
gulp.task('stylus', function() {
  let files = './stylus/**/*.styl',
      destPath = './webroot/css';
  return gulp.src( files )
    .pipe( plumber() )
    .pipe( stylus() )
    .pipe( gulp.dest( destPath ) );
});

次のようなファイル構成だったとき

/stylus
  |- main.styl
  |- /page
       |- unique.styl

👇 gulpでコンパイル

/webroot
  |- /css
      |- main.css
      |- /page
           |- unique.css

gulp.src()に渡されるパスの**に該当する部分のディレクトリがそのまま出力されます。

gulp-rename でリネームする場合

引数にリネームされるファイル名をそのまま入れるとディレクトリ構造は維持されない

// gulpfile.js
const rename = require('gulp-rename');
gulp.task('stylus', function() {
  let files = './stylus/**/*.styl',
      destPath = './webroot/css';
  return gulp.src( files )
    .pipe( plumber() )
    .pipe( stylus() )
    .pipe( rename( 'page.css' ) )
    .pipe( gulp.dest( destPath ) );
});

👇 gulpでコンパイル

/webroot
  |- /css
      |- page.css

gulp.dest で指定されたパス直下にリネームに渡したファイル名でそのまま出力されます。(stylusは2ファイルあるけど同一ファイル名で上書きされるので最終的にcssは1ファイルのみ出力されます)

function か hash を使ってリネームするとディレクトリ構造が維持される

rename via function

const rename = require('gulp-rename');
gulp.task('stylus', function() {
  let files = './stylus/**/*.styl',
      destPath = './webroot/css';
  return gulp.src( files )
    .pipe( plumber() )
    .pipe( stylus() )
    .pipe( rename(function(path) {
      path.basename = 'page';
      console.log( path.dirname ); // ディレクトリ名が入っている
    }) )
    .pipe( gulp.dest( destPath ) );
});

rename via hash

const rename = require('gulp-rename');
gulp.task('stylus', function() {
  let files = './stylus/**/*.styl',
      destPath = './webroot/css';
  return gulp.src( files )
    .pipe( plumber() )
    .pipe( stylus() )
    .pipe( rename({
      basename: 'page'
    }) )
    .pipe( gulp.dest( destPath ) );
});

👇 gulpでコンパイル

/webroot
  |- /css
      |- page.css
      |- /page
           |- page.css

gulp.src()に渡されるパスの**に該当する部分のディレクトリ名がfunctionならpath.dirname、hashならdirnameにデフォルトで入っているので、ディレクトリも構造を維持したまま出力されます。

dirname is the relative path from the base directory set by gulp.src to the filename.
gulp.src() uses glob-stream which sets the base to the parent of the first directory glob (*, **, [], or extglob). dirname is the remaining directories or ./ if none. glob-stream versions >= 3.1.0 (used by gulp >= 3.2.2) accept a base option, which can be used to explicitly set the base.
[出典] gulp-rename - npm

 
gulpでディレクトリ構造を維持したままリネームして出力したい場合はgulp-renameでfunctionかhashを使う方法でリネームさせればOKなようです
gulp.src()の第2引数に渡せるbaseオプションの使いみちがいまいち理解できてないので、もっと便利にリネームして出力する方法があるのかもしれません。


Atomic Design ~堅牢で使いやすいUIを効率良く設計する

Atomic Design ~堅牢で使いやすいUIを効率良く設計する