2017-02-12 132 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) 

})