node.js - 如何使用 gulp-handlebars 缩小 Handlebars 模板

标签 node.js gulp handlebars.js

我有以下 Handlebars 结构:

├── 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知道,如果进程在处理管道时产生错误,它必须关闭源。

谢谢! :)

最佳答案

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

} )

关于node.js - 如何使用 gulp-handlebars 缩小 Handlebars 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183755/

相关文章:

android - 如何使用 Node 服务器验证 Android Google 登录

node.js - 如何在 Mongoose 中为属性设置自定义 setter ?

javascript - 如何使用 gulp 复制文件并将其移动到父文件夹?

node.js - 如何使用 JWT 在 Express 中为单个路由(无代码重复)验证多种类型用户的身份验证 token ?

node.js - 在终端错误中启动 Node/express 项目

laravel - Ubuntu Laravel 上的 Gulp 安装错误

javascript - 如何使用 gulp-jasmine、gulp-jasmine-browser 或 gulp-jasmine-phantom 测试我的功能?

javascript - Handlebars 表单提交不起作用

json - Handlebars block 助手 : each with sort

javascript - meteor .js : how to pass the data context of one helper to another helper?