将主要的凉亭文件(js,css,scss,图像)解析为通过Gulp进行分发

时间:2015-09-28 13:33:08

标签: node.js gulp bower

我们最近从使用PHP资产管理器切换到Gulp。我们使用bower来引入我们的前端包及其依赖项。 使用只有'main'中列出的JS文件的简单Bower包非常简单并且很容易完成。 使用'main-bower-files',我们获取所需的js文件,并将它们连接成一个脚本文件,然后发送到我们的站点/脚本文件夹。 我们可以收集并移动到我们网站中的字体/文件夹的字体。 然后我们碰壁了...如何处理相应的css / scss文件中的图像及其路径。 为了使事情更复杂,我们希望图像保留一些​​原始文件夹布局,以便它们不会被覆盖。 我们想要抓住css和scss(我们使用libsass)文件并将它们与我们自己的样式合并到一个.css文件中。 但是我们怎样才能确保他们仍然能够找到随之而来的图像。

所需的文件夹布局如下:

bower.json
gulpfile.js
package.json
bower_components/
site/
  - css/styles.css
  - fonts/
  - images/
    - bower-package-a/
      - arrow.png
      - gradient.png
      - themea-a/
        - arrow.png
      - theme-b/
        - arrow.png
    - bower-package-b/
      - arrow.png
      - gradient.png
  - script/

到目前为止,这是我们的Gulp文件:

// Include gulp
var gulp = require('gulp');

// Include Plugins
var bower           = require('gulp-bower');
var browserSync     = require('browser-sync').create();
var concat          = require('gulp-concat');
var del             = require('del');
var filter          = require('gulp-filter');
var gutil           = require('gulp-util');
var imagemin        = require('gulp-imagemin');
var jshint          = require('gulp-jshint');
var mainBowerFiles  = require('main-bower-files');
var merge           = require('merge-stream');
var newer           = require('gulp-newer');
var plumber         = require('gulp-plumber');
var pngquant        = require('imagemin-pngquant');
var rename          = require('gulp-rename');
var sass            = require('gulp-sass');
var sourcemaps      = require('gulp-sourcemaps');
var changed         = require('gulp-changed');
var parallel        = require("concurrent-transform");
var os              = require("os");
var imageResize     = require('gulp-image-resize');
var spritesmith     = require('gulp.spritesmith');
var uglify          = require('gulp-uglify');

// Paden
var bowerDest       = 'site/script/lib/bower';
var imgSrc          = 'src/images/**';
var imgDest         = 'site/images';
var spriteImgDest   = './src/images/sprite/';
var scriptSrc       = 'src/script/**/*.js';
var scriptDest      = 'site/script';
var stylesSrc       = 'src/styles/styles.scss';
var stylesDest      = 'site/css';

// Helpers
var onSassError = function(error) {
    gutil.log('Sass Error', gutil.colors.red('123'));
    gutil.beep();
    console.log(error);
    this.emit('end');
}

// Clean images Task
gulp.task('clean:images', function () {
    return del([imgDest]);
});

// Clean script Task
gulp.task('clean:script', function () {
    return del([scriptDest]);
});

// Clean image Task
gulp.task('clean:styles', function () {
    return del([stylesDest]);
});

// Lint Task
gulp.task('lint', function() {
    return gulp.src(scriptSrc)
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
    ;
});

// Sass Task
gulp.task('sass', ['sprite'], function() {
     return gulp.src(stylesSrc)
        .pipe(plumber({
            errorHandler: onSassError
        }))
        .pipe(sourcemaps.init())
        .pipe(sass({
            includePaths: [
              'bower_components/compass-mixins/lib',
              'bower_components/foundation/scss'
            ],
            outputStyle: 'compressed'
        }))
        .pipe(sourcemaps.write('./map'))
        .pipe(gulp.dest(stylesDest))
        .pipe(browserSync.stream())
    ;
});

// Concatenate & Minify JS
gulp.task('script', function() {
    return gulp.src(scriptSrc)
        .pipe(concat('script.js'))
        .pipe(gulp.dest(scriptDest))
        .pipe(rename('script.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest(scriptDest))
    ;
});

// Voeg de JS bestanden die gebruikt worden vanuit bower samen. Let op: modernizr volgt niet de standaard
// en wordt daarom niet meegenomen in mainBowerFiles(). Deze voegen we dus los toe.
gulp.task('bower:js', function() {
    var modernizr = gulp.src('bower_components/modernizr/modernizr.js')
        .pipe(rename('modernizr.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest(scriptDest))
    ;

    var frontend = gulp.src(mainBowerFiles())
        .pipe(sourcemaps.init())
        .pipe(filter('*.js'))
        .pipe(concat('frontend.min.js'))
        .pipe(uglify())
        .pipe(sourcemaps.write('maps'))
        .pipe(gulp.dest(scriptDest))
    ;

    return merge(modernizr, frontend);
});

// Imagemin Task (compress images)
gulp.task('imagemin', function () {
    return gulp.src([imgSrc, '!src/images/sprite{,/**}'])
        .pipe(newer(imgDest))
        .pipe(imagemin({
            use: [pngquant()]
        }))
        .pipe(gulp.dest(imgDest))
        .pipe(browserSync.stream())
    ;
});

// Compile sass into CSS & auto-inject into browsers
gulp.task('browser-sync', function() {
    // Serve files from the root of this project
    browserSync.init({
        proxy: "localhost/insyde/website_v6_devtools/site"
    });

    // add browserSync.reload to the tasks array to make
    // all browsers reload after tasks are complete.
    gulp.watch("./src/script/**/*.js", ['scripts-watch']);
});

// generate the x1 images from the big ones
gulp.task('generate-small-sprite-images', function () {
    return gulp.src('./src/images/sprite/*-2x.png')
        .pipe(newer(rename(function(path) {
              path.basename = path.basename.slice(0, -3);  //remove @2x label
        })))
        .pipe(parallel(
            imageResize({
                width: '50%',
                height: '50%'
            }), os.cpus().length
        ))
        .pipe(rename(function(path) {
              path.basename = path.basename.slice(0, -3);  //remove @2x label
        }))
        .pipe(gulp.dest(spriteImgDest))
;});

gulp.task('sprite', ['generate-small-sprite-images'], function () {
    var spriteData = gulp.src('./src/images/sprite/**/*.png').pipe(spritesmith({
        imgName: 'sprite.png',
        retinaImgName: 'sprite-2x.png',
        cssName: 'sprite.scss',
        imgPath: '../images/sprite.png', 
        retinaImgPath : '../images/sprite-2x.png', 
        retinaSrcFilter: '**/*-2x.png'
    }));
    // Pipe image stream through image optimizer and onto disk
    var imgStream = spriteData.img
        .pipe(imagemin())
        .pipe(gulp.dest(imgDest));

    // Pipe CSS stream through CSS optimizer and onto disk
    var cssStream = spriteData.css
        .pipe(gulp.dest('./src/styles/'));

    // Return a merged stream to handle both `end` events
    return merge(imgStream, cssStream);
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch('./src/script/**/*.js', ['lint', 'script']);
    gulp.watch('./src/styles/**/*.scss', ['sass']);
    gulp.watch('./src/images/**', ['imagemin']);
    gulp.watch('./templates/**/*.html').on('change', browserSync.reload);
});

// Default Tasks
gulp.task('default', ['lint', 'sass', 'bower:js', 'script', 'imagemin', 'watch']);
gulp.task('frontend', ['lint', 'sprite', 'sass', 'bower:js', 'script', 'imagemin', 'browser-sync', 'watch']);
gulp.task('clean', ['clean:images', 'clean:script', 'clean:styles']);

// create a task that ensures the `scripts` task is complete before
// reloading browsers
gulp.task('scripts-watch', ['script'], browserSync.reload);   

2 个答案:

答案 0 :(得分:5)

搞定了!

我以此为例:https://github.com/jonkemp/gulp-useref/issues/60#issuecomment-77535822

这些任务的作用是:

<强>亭子:资产 将bower包的'main'属性中定义的所有资产文件(图像和字体)(我们使用main-bower-files找到)复制到site / dist /,同时保留包的原始文件夹布局。< / p>

<强>亭子:样式 解析来自main-bower文件的每个样式表(不包括两个包:foundation和compass-mixins),并重新设置指向我们之前复制的图像和字体的URL。这与示例的不同之处在于,我的情境中的文件不会首先复制到.tmp目录,而是直接处理,然后直接写入site / css文件夹。我连接并缩小了css,同时使用sourcemaps使调试更容易。

//copy bower assets that need copying
gulp.task('bower:assets', function() {
    return gulp.src(mainBowerFiles(), {
        base: './bower_components'
    })
    .pipe(filter([
        '**/*.{png,gif,svg,jpeg,jpg,woff,eot,ttf}',
        '!foundation/**/*',
        '!compass-mixins/**/*'
    ]))
    .pipe(gulp.dest('./site/dist'));
});

//generate bower stylesheets with correct asset paths
gulp.task('bower:styles', function() {
    return gulp.src(mainBowerFiles(), {
        base: './bower_components'
    })
    .pipe(filter([
        '**/*.{css,scss}',
        '!foundation/**/*',
        '!compass-mixins/**/*'
    ]))
    .pipe(foreach(function(stream, file) {
        var dirName = path.dirname(file.path);
        return stream
            .pipe(rework(reworkUrl(function(url) {
                var fullUrl = path.join(dirName, url);
                if (fs.existsSync(fullUrl)) {
                    bowerCopyFiles.push(fullUrl);
                    console.log(path.relative('css', fullUrl).replace(/bower_components/, 'dist'));
                    return path.relative('css', fullUrl).replace(/bower_components/, 'dist');
                }
                return url;
            })));
    }))
    .pipe(sourcemaps.init())
    .pipe(concat('bower.css'))
    .pipe(minifyCss())
    .pipe(sourcemaps.write('./map'))
    .pipe(gulp.dest(stylesDest));
});

这一切导致以下目录结构:

  • bower_components
  • 站点
    • CSS
      • bower.css
    • DIST
      • 亭子组分-一个
        • 图像
          • arrow.png
          • gradient.png
      • 亭子组分-B
        • 图像
          • arrow.png
          • gradient.png

答案 1 :(得分:1)

另一种选择是使用gulp-bower-normalize包,它将从main-bower-files获取管道输出,然后根据包和文件扩展名将它们拆分,例如。

gulp.src(mainBowerFiles(), { base: 'bower_components' })
    .pipe(bowerNormalize({ bowerJson: './bower.json'  }))
    .pipe(gulp.dest('assets/vendor'));

您可能还必须调整bower.js中的主要文件,但它的效果非常好。如果您使用的是Bootstrap ......

<强> bower.json:

{
    ...
    "dependencies": {
        "bootstrap": "^3.3.6",
        ...
    },
    "overrides": {
        "bootstrap": {
            "main": [
                "dist/css/bootstrap.min.css",
                "dist/js/bootstrap.min.js",
                "fonts/glyphicons-halflings-regular.eot",
                "fonts/glyphicons-halflings-regular.svg",
                "fonts/glyphicons-halflings-regular.ttf",
                "fonts/glyphicons-halflings-regular.woff",
                "fonts/glyphicons-halflings-regular.woff2"
            ],
            "normalize": {
                "fonts": ["*.eot", "*.svg", "*.ttf", "*.woff", "*.woff2"]
            }
        }
    } 
}

......它会生成以下结构:

assets/
|-- vendor/
    |-- bootstrap/
        |-- css/
        |   |-- bootstrap.min.css
        |
        |-- fonts/
        |   |-- glyphicons-halflings-regular.eot
        |   |-- glyphicons-halflings-regular.svg
        |   |-- glyphicons-halflings-regular.ttf
        |   |-- glyphicons-halflings-regular.woff
        |   |-- glyphicons-halflings-regular.woff2
        |
        |-- js/
            |-- bootstrap.min.js

另一个不错的选择是flatten结构,这在捆绑供应商文件时可能更有用。