diff --git a/README.md b/README.md index 6050f13..6c893c1 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ exports.views = () => { - `opts.locals` (`Object`): Locals to compile the Pug with. You can also provide locals through the `data` field of the file object, e.g. with [`gulp-data`][gulp-data]. They will be merged with `opts.locals`. - `opts.data` (`Object`): Same as `opts.locals`. - `opts.client` (`Boolean`): Compile Pug to JavaScript code. +- `opts.name` (`string | ((file: VinylFile) => string)`): The name of your client side template function, when `opts.client` is set to `True`. When passed as a function, takes current Pug file as an argument. - `opts.pug`: A custom instance of Pug for `gulp-pug` to use. - `opts.verbose`: display name of file from stream that is being compiled. diff --git a/index.d.ts b/index.d.ts index 3527a5e..1f04b30 100644 --- a/index.d.ts +++ b/index.d.ts @@ -27,6 +27,12 @@ declare namespace GulpPug { */ client?: boolean; + /** + * If passed as a string, used as the name of your client side template function. If passed as a function, + * it is called with a pug template file as an argument, to obtain a name of client side template function. + */ + name?: string | ((file: VinylFile) => string); + /** * A custom instance of Pug for `gulp-pug` to use. */ diff --git a/index.js b/index.js index 8280222..e8e1995 100644 --- a/index.js +++ b/index.js @@ -9,6 +9,7 @@ const vinylContents = require('vinyl-contents'); module.exports = function gulpPug(options) { const opts = Object.assign({}, options); + const namefunc = typeof opts.name === 'function' ? opts.name : undefined; const pug = opts.pug || opts.jade || defaultPug; opts.data = Object.assign(opts.data || {}, opts.locals || {}); @@ -37,6 +38,9 @@ module.exports = function gulpPug(options) { log('compiling file', file.path); } if (opts.client) { + if (typeof namefunc === 'function') { + opts.name = namefunc(file); + } compiled = pug.compileClient(contents, opts); } else { compiled = pug.compile(contents, opts)(data); diff --git a/test/test.js b/test/test.js index f490de2..9a24553 100644 --- a/test/test.js +++ b/test/test.js @@ -153,6 +153,32 @@ describe('test', function () { ); }); + it('should name the compiled JS function using name option', function (done) { + function name(file) { + if (!file || !file.name) { + return 'template'; + } + return '__' + path.basename(file.path, '.pug') + '__'; + } + + const templateFilename = 'helloworld.pug'; + + function assert(files) { + expect(files.length).toEqual(1); + const newFileContent = files[0].contents.toString(); + expect(newFileContent).toContain("function " + name(templateFilename) + "("); + } + + pipe( + [ + from.obj([getFixture(templateFilename)]), + task({ client: true, name }), + concat(assert), + ], + done + ); + }); + it('should always return contents as buf with client = true', function (done) { function assert(files) { expect(files.length).toEqual(1);