수색…


통사론

  • 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>);

비고

계속 읽기 - 기본 작업 만들기 및 브라우저 동기화 설정

참고 문헌

Gulp 워크 플로우 자동화를위한 단계별 가이드 제 블로그를 설명하는 절대 초보자를위한 자동화

Package.JSON의 모든 플러그인로드

가정을 설치하는 방법에 대해 알고 있다면 프로젝트 루트 폴더 아래에있는 package.json의 모든 gulp 종속성을 요구하는 것으로 넘어 갑니 다.

아직 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')();

노트

우리가이 기사에서 갖게 될 많은 예들에서, 우리는 별칭

  1. $로 꿀꺽 꿀꺽 마시고
  2. $$로서 gulp-load-plugins

순전히 타이핑의 용이성을 위해.

응답 성있는 이미지를위한 플러그인 설치 | Css Minification | Js minification

우리의 목표는

  1. 다양한 너비의 이미지 배터리를 생성하고 크기를 축소하여 이미지를 너비와 크기에 맞게 적절하게 조정합니다.
  2. 린트 당신의 자바 스크립트
  3. 애셋 최소화 - JS / CSS / HTML - 가장 가벼운 코드보다 가벼운 호스트 가능
  4. css / js / image 파일에서 변경 사항을 확인하고 최적화를 다시 작성하십시오.
  5. 개발중인 변경 사항을 사이트를 제공하는 브라우저로 동기화합니다.

우리는 많은 플러그인을 필요로하므로, 모두 설치하십시오. 이 모든 것을 프로젝트의 루트 폴더에서 실행하십시오.

이미지 처리 플러그인

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는 파이프 라인의 각 플러그인에 대해 glob과 일치하는 각 개별 파일에서 스트림과 파이프 파이프를 만드는 것입니다. 각 플러그인은 파일이 전달되고 $ .dest에 도달 할 때까지 메모리의 내용을 수정합니다. / $ .src로 스트리밍 된 파일을 만듭니다.

어디서 ,

$ -> 꿀꺽 꿀꺽 마심

$$ -> gulp-load-plugins

자산 최적화 및 확장


따라서 optimiser 함수를 작성하기 전에 몇 가지 캐싱 플러그인을 설치해야합니다.

bash $ npm install --save-dev gulp-cached
bash $ npm install --save-dev gulp-remember

왜 두 개의 캐시 어쩌구 궁금해! 꿀꺽 꿀꺽 마심 캐싱 은 변경된 내용이나 새 내용 만 파이프 라인을 통해 다른 플러그인으로 전달합니다. 우리가 변화하지 않고 파일을 원하기 때문에 그래서, 자산 당 하나의 파일로 합치에 사용되는 |뿐만 아니라, 우리가 할뿐만 아니라 기억 꿀꺽 필요 CSS (JS) 꿀꺽 - 캐시

먼저 gulp-cached 를 사용하여 변경된 파일 목록을 작성합니다

두 번째로, 우리는 꿀꺽 꿀꺽 마셔야 합니다. 그 목록에 의해 전달 된 모든 파일을 메모리에 보관하는 것을 잊지 마십시오.

첫 번째 실행 : 파일이 캐싱되지 않으므로 꿀꺽 꿀꺽 마셔서 꿀꺽 꿀꺽 마셔야합니다.

후속 실행 : 변경되거나 새로 만들어진 파일 만 덤프 캐시로 파이프됩니다. 현재 파일의 내용이 변경되었으므로 gulp-remember는 캐시를 업데이트합니다.

Cool, 첫 번째 최적화 도구를 작성하겠습니다.

스타일 최적화 도구


// 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-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-load-plugins

$ .src -> src로 전달 된 glob와 일치하는 파일 스트림을 만듭니다.

$ .dest -> 조작 된 파일을 지정된 경로에 저장합니다.

반응 형 이미지 생성

이제 이미지 프로세싱으로 넘어 갑시다. 그래서, 목표는 당신이 봉사 할 각 이미지에 맞는 크기의 배열을 갖는 것입니다.

왜?

다양한 범위의 이미지가 필요한 이유를 이해하려면 다양한 해상도의 장치가있을 가능성을 고려해야합니다. 많은 픽셀 화없이 이미지를 확장해야합니다. 동시에 포함 된 너비에 맞는 이미지 하나를 다운로드하고 가능한 가장 작은 크기의 이미지를 다운로드하여 페이지로드 시간을 개선해야합니다. 에릭 포티스 (Eric Portis)가 쓴 것처럼 학술 블로그가 있습니다. 미디어 쿼리의 비효율을 강조하고 srcsets 및 크기와 같은 개념을 이해하기위한 포괄적 인 가이드 역할을합니다.

Eric Portis의 서사시는 여기를 참조 하십시오.

이제 우리의 기능은 글로브와 너비를 입력으로 받아야하고 매직을 실행하고 각각의 실행이 생성하는 파일을 대상으로 푸시하고 응답 된 이미지를 축소합니다.

첫 번째 예제에서는 두 개의 이미지 압축 플러그인 설치했습니다.

이 플러그인들은 "gulp-"라는 접두어로 시작 하지 않기 때문에 수동으로 gulpfile에로드해야합니다.

그래서 우리는 gulpfile 맨 위에서 gulp-load-plugins 선언을 한 후 수동으로 요구합니다.

이렇게 :

var compressJpg = require('imagemin-jpeg-recompress');
var pngquant = require('imagemin-pngquant');

꿀꺽 꿀꺽 반응이 날카로운 이미지 프로세서와 함께 제공된다는 점은 주목할 가치가 있습니다. FAAAAR를 통해 상상하는 것보다 낫습니다. 샤프는 이미지를 원하는 너비로 잘라 내기 위해 꿀꺽 꿀꺽 반응에 의해 사용되는 것입니다.

당신은 포괄적 인 구성 매개 변수 목록을 위해 gulp-responsive-configuration-options을 볼 수 있습니다. 나는 단지 사용했다.

  • width - 이미지를 너비 w로 자르고, 매개 변수로 전달합니다.
  • rename - 이미지 이름에 접미사를 추가하여 고유하게 유지합니다.

아래의 내 구성 기능에서. 우리 함수는 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-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을 최적화하기 위해 위에서 정의 된 함수
  • 이미지 당 여러 개의 이미지를 생성하는 함수입니다.

우리가 지금해야 할 일은 필요할 때 그들을 호출하는 것입니다.

앞에서 정의한 구문에 따라 작업을 작성하겠습니다.

/*
* $.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();

});


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow