2017-02-12 97 views
1

我有以下车把结构:如何用一口车把来缩小车把模板

├── gulpfile.js 
└── source/ 
    └── templates/ 
     ├── view1/ 
     │ └── template11.handlebars 
     └── view2/ 
      └── template21.handlebars 

并获得这样的:

└── target/ 
    └── js/ 
     ├── view1.min.js  
     └── view2.min.js 

的问题是如何创造实际minified的预编译模板。现在我只是得到了开放的预编译的js。

gruntfile.js是:

const pump = require('pump') 
const rename = require('gulp-rename') 
const handlebars = require('gulp-handlebars') 

gulp.task('build-templates', (done) => { 

    const views = [ 
     'view1', 
     'view2' 
    ] 

    let pipe = [] 

    views.forEach((view) => { 
     pipe.push(gulp.src('source/templates/' + view + '/**/*')) 
     pipe.push(handlebars()) 
     pipe.push(rename(view +'.templates.min.js')) 

     // pipe.push(uglify()) <-- this gives me the error: 
     // [13:40:38] GulpUglifyError: unable to minify JavaScript 
     // Caused by: SyntaxError: Unexpected token: punc (:) (line: 1, col: 11, pos: 11)" 

     pipe.push(gulp.dest('target/js')) 
    }) 

    pump(pipe, done) 

}) 

我使用pump只是为了让node.js的知道它有如果一个进程在处理管产生错误关闭源。

谢谢! :)

回答

1

我没有意识到我需要将编译后的代码作为参数包装到Handlebars.template()。在gulp-handlebars文档中明确指出。 :(所以结果是不是一个有效的JS代码和uglify无法处理它。解决方案是:

const pump = require('pump') 
const concat = require('gulp-concat') 
const wrap = require('gulp-wrap') 
const declare = require('gulp-declare') 
const handlebars = require('gulp-handlebars') 
const uglify = require('gulp-uglify') 

gulp.task('build-templates', (done) => { 

    const views = [ 
     'view1', 
     'view2' 
    ] 

    let pipe = [] 

    views.forEach((view) => { 
     pipe.push(gulp.src('source/templates/' + view + '/**/*')) 
     pipe.push(handlebars()) 
     pipe.push(wrap('Handlebars.template(<%= contents %>)')) // <-- this is the key 
     pipe.push(declare({ 
      namespace: 'MyApp.templates', // <-- get easy access to templates 
      noRedeclare: true, // <-- Avoid duplicate declarations 
     })) 
     pipe.push(concat(view + '.templates.js')) // <-- use concat instead of rename to concatenate several templates 
     pipe.push(uglify()) // <-- done 
     pipe.push(gulp.dest('target/js')) 
    }) 

    pump(pipe, done) 

})