gulp
Gulpjsを使用したフロントエンドワークフローの自動化に関する包括的なガイド-1 of 2
サーチ…
構文
- npm install [plugin-name] --save-dev
- npm install [plugin-name] --save
- 関数
<function-name>
(グロブ){$ .SRC(グロブ).pipe([プラグイン1])。パイプ([プラグイン2])...パイプ([プラグインN])。パイプ($ .dest(<destination-name>
)} -
$.task(<taskname> , [dependencies] , <body>);
備考
読書を続ける - デフォルトタスクを作成し、ブラウザ同期を設定する
参考文献
Package.JSONからすべてのプラグインを読み込む
あなたがgulpをインストールする方法を理解しているとすれば、プロジェクトのルートフォルダの下にあるpackage.jsonからのすべての依存関係を要求するようにしましょう。
あなたがまだgulpfileを持っていない場合は、名前が空の空のファイルを作成してください
gulpfile.js
第一に、我々は麻薬を必要とする。そのようです:
var $ = require('gulp');
次に、すべてのプラグインをgulpfileにロードしましょう。以下のスニペットで
注意
この読み物に含まれるすべてのスニペットのコメントを読んでください。すべての機能についてより詳細な情報を提供しています。
/*
require gulp-load-plugins, and call it
gulp-load-plugins will require individually,
all the plugins installed in package.json at the root directory
these required plugins, are lazy loaded
that is, gulp-load-plugins will only require them when they are referenced in this file
plugins are available for perusal, via camelcased names, minus gulp
eg: gulp-clean-css is accessed by $$.cleanCss
*/
var $$ = require('gulp-load-plugins')();
注意
多くの例を通して、記事では別名
- $と
- $$としてのgulp-load-plugins
純粋にタイピングのためです。
レスポンスイメージのためのプラグインのインストール| Cssのマイニング| Jsのミニソフト
我々の目標は、
- さまざまな幅の画像のバッテリーを生成し、それらを縮小することによって、画像を幅に合わせて適切に拡大縮小します
- リントあなたのJavascript
- あなたの資産を最小限に抑える - JS / CSS / HTML。これにより、軽いコードよりも軽い
- 変更のためのcss / js / imageファイルを見て、最適化を再構築する
- 開発中の変更をサイトにアクセスするブラウザに同期させる。
いくつかのプラグインが必要なので、すべてインストールしてください。これらのすべてをプロジェクトのルートフォルダで実行してください。
画像処理プラグイン
bash $ npm install --save-dev gulp-responsive
bash $ npm install --save-dev gulp-imagemin
bash $ npm install --save-dev imagemin
bash $ npm install --save-dev imagemin-jpeg-recompress
bash $ npm install --save-dev imagemin-pngquant
資産オプティマイザプラグイン
bash $ npm install --save-dev gulp-clean-css
bash $ npm install --save-dev gulp-uglify
bash $ npm install --save-dev gulp-minify-html
bash $ npm install --save-dev gulp-jshint
bash $ npm install --save-dev gulp-concat
bash $ npm install --save-dev gulp-autoprefixer
ガルプ関数の解剖学
[Function <name>] (glob) {
$.src(glob)
.pipe([plugin 1])
.pipe([plugin 2])
.
.
.
.pipe([plugin n])
.pipe( $.dest(<destination-name>)
}
注意
pipeはglob入力に一致するすべてのファイルをプラグイン(この場合はminifyhtml)にストリームするメソッドです。
次のように簡単に描くことができます:
$ .srcは、ストリームとパイプパイプをパイプライン内の各プラグインにマッチする個々のファイルからビルドします。各プラグインはファイルが渡され、$ .destに達するまでその内容がメモリに変更されます。 / $ .srcでストリームされたファイルを作成する
ここで 、
$ - > gulp
$$ - > gulp-load-plugins
資産の最適化と縮小
だから、オプティマイザ関数を書く前に、いくつかのキャッシングプラグインをインストールする必要があります。
bash $ npm install --save-dev gulp-cached
bash $ npm install --save-dev gulp-remember
なぜあなたは2つのキャッシュええ! gulp-cachedは 、変更されたコンテンツまたは新しいコンテンツのみをパイプラインを介して他のプラグインに渡します。そのため、変更のないファイルをアセットごとに1つのファイル(css | js)に連結するために使用するため、 gulp-cachedに加えてgulp- rememberも必要です
まず、 gulp-cachedを使用して、変更されたファイルのリストを作成します
第二に、私たちはgulpを必要とします。そのリストによって渡されるすべてのファイルをメモリに保存することを忘れないでください。
最初の実行:ファイルがキャッシュされていないので、gulp-cachedはすべてのファイルをパスして覚えています
後続の実行:変更されたファイルまたは新しいファイルのみがgulp-cachedによってパイプされます。現在のファイルの内容が変更されたので、gulp-rememberはキャッシュを更新します。
クール、最初のオプティマイザを書きましょう
スタイルオプティマイザ
// Goal
/*
1. cache existing files on the first run
2. each file ,
a. Is autoprefixed with cross browser compatible prefixes for any css property ( justify-content for e.g)
b. Is concatenated into app.css
3. app.css is minified
4. On subsequent runs , the above process is implemented on file modifications/additions only
*/
/*
*@src - input a glob pattern - a string eg 'images/**/*' or '**/*.css' or, an array eg ['glob1','glob2']
*/
var optimizeStyles = function(src) {
return $.src(src).
pipe($$.cached('styles')).
pipe($$.autoprefixer({
browsers: ['last 2 versions']
})).
pipe($$.remember('auto-prefixed-stylesheets')).
pipe($$.concat('app.css')).
pipe($.dest('build/css')).
pipe($$.cleanCss()).
pipe($$.rename({
suffix: '.min'
})).
pipe($.dest('build/css'))
}
注意
$ - > gulp
$$ - > gulp-load-plugins
$ .src - > srcとして渡されたglobと一致するファイルストリームを構築する
$ .dest - >操作されたファイルを指定されたパスに保存する
スクリプトオプティマイザ
// Goal
/*
1. cache existing files on the first run
2. each file ,
a. Is linted with jshint
b. Is concatenated into app.js
3. app.js is minified
4. On subsequent runs , the above process is implemented on file modifications/additions only
*/
/*
*@src - input a glob pattern - a string eg 'js/**/*' or '**/*.js' or, an array eg ['glob1','glob2']
*/
var optimizeScripts = function(src) {
return $.src(src).
pipe($$.cached('scripts')).
pipe($$.jshint()).
pipe($$.jshint.reporter('default')).
pipe($$.jshint.reporter('fail')).
pipe($$.remember('linted-scripts')).
pipe($$.concat('app.js')).
pipe($.dest('build/js')).
pipe($$.uglify()).
pipe($$.rename({
suffix: '.min'
})).
pipe($.dest('build/js'))
}
注意
$ - > gulp
$$ - > gulp-load-plugins
$ .src - > srcとして渡されたglobと一致するファイルストリームを構築する
$ .dest - >操作されたファイルを指定されたパスに保存する
レスポンスイメージを生成する
今度は画像処理に移りましょう。だから、目的は、あなたが提供しようとしている各画像のサイズの配列を持っていることです。
どうして?
なぜ、さまざまな幅の画像が必要なのかを理解するためには、さまざまな解像度のデバイスが存在する可能性があるという事実を熟考する必要があります。我々は、ピクセル化をあまり行わずに画像を拡大縮小する必要があります。同時に、ページの読み込み時間を改善する必要があります。これは、含まれる幅に適合する1つの画像だけをダウンロードし、できるだけ小さい次元でも行うことで、画像の読み込み時間を短縮する必要があります。 Eric Portisが書いたような学問的なブログがあります。これはメディアの質問だけでは効果がないことを強調し、srcsetsやサイズなどの概念を理解する包括的なガイドとして役立ちます。
今、私たちの機能は、入力としてglobを取る必要があり、その魔法を実行し、実行ごとに生成されたファイルを宛先に送り、応答されたイメージを縮小します。
最初の例で 2つの画像圧縮プラグインをインストールしました
これらのプラグインは、「gulp-」接頭辞で始まっていないので、我々は手動で私たちのgulpfileにそれらをロードする必要があります。
だから、gulp-load-plugins宣言をgulpfileの先頭に置いて、手動でそれらを要求してみましょう。
そのようです:
var compressJpg = require('imagemin-jpeg-recompress');
var pngquant = require('imagemin-pngquant');
派手なイメージプロセッサーは、FAAAARの想像を絶するイメージプロセッサーよりも優れていることに注意してください。シャープは、あなたのイメージを所望の幅に切り抜くために、敏捷性に反応するものが使用しているものです。
gulp-responsive-configuration-optionsを見て、構成パラメータの包括的な一覧を調べることができます。私は使用しただけです
- width - イメージを幅wにトリミングし、パラメータとして渡します。
- 名前の変更 - イメージ名に接尾辞を追加して、それが一意になるようにする
以下の私の設定機能で。 glob関数を介して解読されたすべての一致する画像に対して、入力として渡された幅に画像をトリミングします。各イメージは、jpeg-recompressまたはpngquantを使用して圧縮され、ビルド/イメージ内に保存されます。
そのことを念頭に置いて、私たちの機能は次のようになります:
/*
@generateResponsiveImages
*@Description:takes in a src of globs, to stream matching image files , a width,
*to resize the matching image to, and a dest to write the resized and minified files to
*@src - input a glob pattern - a string eg 'images/** /*' or 'images/*' or, an array
eg ['glob1','glob2']
*@return returns a stream
*/
var generateResponsiveImages = function(src, width, dest) {
//declare a default destination
if (!dest)
dest = 'build/images';
//case 1: src glob - images/**/*
// the base is the directory immediately preceeding the glob - images/ in this case
//case 2: images/fixed/flourish.png : the base here is images/fixed/ - we are overriding
// that by setting base to images.This is done so that, the path beginning after images/
// - is the path under our destination - without us setting the base, dest would be,
//build/images/flourish.png.But with us setting the base, the destination would be
// build/images/fixed/flourish.png
return $.src(src, {
base: 'images'
})
//generate resized images according to the width passed
.pipe($$.responsive({
//match all pngs within the src stream
'**/*.png': [{
width: width,
rename: {
suffix: '-' + width
},
withoutEnlargement: false,
}],
//match all jpgs within the src stream
'**/*.jpg': [{
width: width,
rename: {
suffix: '-' + width
},
progressive: true,
withoutEnlargement: false,
}]
}, {
errorOnEnlargement: false,
errorOnUnusedConfig: false,
errorOnUnusedImage: false
}))
//once the file is resized to width, minify it using the plugins available per format
.pipe($$.if('*.jpg', compressJpg({
min: 30,
max: 90,
target: 0.5
})()))
//use file based cache gulp-cache and it will minify only changed or new files
//if it is not a new file and if the contents havent changed, the file is served from cache
.pipe($$.cache($$.imagemin({
verbose: true
})))
//write to destination - dest + path from base
.pipe($.dest(dest));
}
注意
$ - > gulp
$$ - > gulp-load-plugins
$ .src - > srcとして渡されたglobと一致するファイルストリームを構築する
$ .dest - >操作されたファイルを指定されたパスに保存する
その他の参考文献
HTMLマイナー
*
*@minifyHtml
*Description:takes in a glob src, and minifies all '.html' files matched by the glob
*@src - input a glob pattern - a string eg '/**/*.html /*' or '*.html' or, an array eg ['glob1','glob2']
*@dest=file.base means, the modified html file will be in the same directory as the src file being minified
*often means, the process is just a modification on the existing src file
*@return returns a stream
*/
var minifyHtml = function(src) {
return $.src(src)
.pipe($$.minifyHtml())
.pipe($.dest(function(file) {
//file is provided to a dest callback -
// Refer here https://github.com/gulpjs/gulp/blob/master/docs/API.md#path
return file.base;
}));
}
ガルプ課題の解剖学
タスク定義の解剖はそうです:
$.task(<taskname> , [dependencies] , <body>);
依存関係は、定義している現在のタスクが実行される前に完了しなければならないタスクの配列です。さらに、デフォルトの非同期機能の代わりに同期実行を強制するようなもの。
ガルスタスクの追加
だから、私たちは今
- スタイルを最適化するために上で定義された関数
- スクリプトを最適化するために定義された関数
- HTMLを最適化するために定義された関数
- 1画像あたり複数の画像を生成する関数
今必要なのは、必要なときに呼び出すことだけです。
前に定義した構文に従ってタスクを記述しましょう
/*
* $.task('name','dependency array',function)
results in building a task object as below
task:{
'name':name,
'dep':[array of dependencies],
'fn':function
}
*/
//*@return returns a stream to notify on task completion
$.task('optimizeHtml', function() {
var src = ['**/*.html', '!{node_modules}/**/*.html'];
return minifyHtml(src);
});
//*@return returns a stream to notify on task completion
$.task('optimizeScripts', function() {
var src = ['js/**/*.js'];
return optimizeScripts(src);
});
//*@return returns a stream to notify on task completion
$.task('optimizeStyles', function() {
var src = ['css/**/*.css', 'fonts/google/**/*.css'];
return optimizeStyles(src);
});
//Take in a callback to ensure notifying the gulp engine, that the task is done
//required since, you are not returning a stream in this task
$.task('generateResponsiveImages', function(callback) {
var src = ['images/**/*.{jpg,png}'];
for (var i = widths.length - 1; i >= 0; i--) {
generateResponsiveImages(src, widths[i]);
}
callback();
});