gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:55:33 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com