如何使用gulp-Handlebars缩小把手模板

时间:2017-02-12 02:58:42

标签: node.js gulp handlebars.js

我有以下把手结构:

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

得到这个:

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

问题是如何创建实际缩小的预编译模板。现在我只是打开预编译的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 个答案:

答案 0 :(得分:2)

我没有意识到我需要将编译后的代码作为参数包装到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 )

} )