A clean, whitespace-sensitive template language for writing HTML
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Browser-compatible template compilation for client-side rendering. These functions generate standalone JavaScript code that can run in browsers without Node.js dependencies, enabling dynamic template rendering on the client side.
Compiles a Pug template to JavaScript source code for browser execution.
/**
* Compile template to JavaScript source for browser use
* @param str - Pug template source code
* @param options - Client compilation options
* @returns JavaScript source code string
*/
function compileClient(str, options);Usage Examples:
const pug = require('pug');
// Basic client compilation
const clientJS = pug.compileClient('p Hello #{name}!');
console.log(clientJS);
// Output: function template(locals) { ... return "<p>Hello " + pug.escape(locals.name) + "!</p>"; }
// With options
const clientJS2 = pug.compileClient(`
div.user-card
h3= user.name
p= user.email
if user.verified
span.badge Verified
`, {
name: 'userCardTemplate',
compileDebug: false,
inlineRuntimeFunctions: true
});
// Save to file for browser use
const fs = require('fs');
fs.writeFileSync('templates/user-card.js', clientJS2);Compiles a Pug template file to JavaScript source code with caching support.
/**
* Compile template file to client-side JavaScript
* @param path - Path to Pug template file
* @param options - Client compilation options
* @returns JavaScript source code string with caching
*/
function compileFileClient(path, options);Usage Examples:
const pug = require('pug');
// Compile file to client JavaScript
const clientJS = pug.compileFileClient('./templates/product-list.pug', {
name: 'productListTemplate',
inlineRuntimeFunctions: false
});
// With caching for build processes
const clientJS2 = pug.compileFileClient('./templates/modal.pug', {
cache: true,
name: 'modalTemplate',
compileDebug: false
});
// Build step: compile all templates
const templates = [
'user-profile.pug',
'product-card.pug',
'navigation.pug'
];
templates.forEach(template => {
const js = pug.compileFileClient(`./src/templates/${template}`, {
name: template.replace('.pug', 'Template'),
inlineRuntimeFunctions: true
});
fs.writeFileSync(`./dist/templates/${template}.js`, js);
});Compiles a template with full dependency tracking for build systems.
/**
* Compile template with dependency tracking
* @param str - Pug template source code
* @param options - Compilation options
* @returns Object with body (JavaScript code) and dependencies array
*/
function compileClientWithDependenciesTracked(str, options);Usage Examples:
const pug = require('pug');
// Template with includes/extends
const result = pug.compileClientWithDependenciesTracked(`
extends layout.pug
block content
include components/header.pug
div.main-content
h1= title
p= content
`, {
filename: './views/page.pug',
basedir: './views'
});
console.log(result.body); // JavaScript template code
console.log(result.dependencies);
// ['./views/layout.pug', './views/components/header.pug']
// Use in build system for file watching
const watchFiles = [result.filename, ...result.dependencies];
watchFiles.forEach(file => {
fs.watchFile(file, () => {
console.log(`Template dependency ${file} changed, rebuilding...`);
// Rebuild template
});
});Client compilation functions accept specialized options:
interface ClientCompilationOptions extends CompilationOptions {
/** Name for the generated template function (default: 'template') */
name?: string;
/** Include runtime functions inline (default: false for compileClient) */
inlineRuntimeFunctions?: boolean;
/** Generate module.exports syntax for CommonJS (default: false) */
module?: boolean;
/** Enable template caching for compileFileClient */
cache?: boolean;
}The generated client-side templates can be used in browsers:
<!-- Include Pug runtime (if not inlined) -->
<script src="https://unpkg.com/pug-runtime@2.0.5/index.js"></script>
<!-- Include your compiled template -->
<script src="templates/user-card.js"></script>
<script>
// Use the compiled template
const html = userCardTemplate({
user: {
name: 'Alice Smith',
email: 'alice@example.com',
verified: true
}
});
document.getElementById('container').innerHTML = html;
</script>Generate templates compatible with different module systems:
// CommonJS module
const clientJS = pug.compileClient('p Hello #{name}!', {
name: 'myTemplate',
module: true,
inlineRuntimeFunctions: false
});
// Generates: var pug = require("pug-runtime"); ... module.exports = myTemplate;
// Inline runtime (no external dependencies)
const clientJS2 = pug.compileClient('p Hello #{name}!', {
name: 'myTemplate',
inlineRuntimeFunctions: true
});
// Generates: function myTemplate(locals) { /* all runtime code included */ }Template Bundling:
// Bundle multiple templates into one file
const templates = {
userCard: pug.compileClient(fs.readFileSync('./user-card.pug', 'utf8'), {
name: 'userCard',
inlineRuntimeFunctions: true
}),
productList: pug.compileClient(fs.readFileSync('./product-list.pug', 'utf8'), {
name: 'productList',
inlineRuntimeFunctions: true
})
};
const bundle = `
window.Templates = {
${templates.userCard},
${templates.productList}
};
`;
fs.writeFileSync('./dist/templates.js', bundle);Webpack Integration:
// webpack.config.js
const pug = require('pug');
module.exports = {
module: {
rules: [
{
test: /\.pug$/,
use: [
{
loader: 'apply-loader'
},
{
loader: 'pug-loader',
options: {
root: path.resolve(__dirname, 'src/templates')
}
}
]
}
]
}
};
// Usage in JavaScript
import template from './templates/user-profile.pug';
const html = template({ user: userData });Runtime Function Inlining:
// Without inlining - requires pug-runtime
const template1 = pug.compileClient('p #{name}', {
inlineRuntimeFunctions: false
});
// Needs: <script src="pug-runtime.js"></script>
// With inlining - standalone
const template2 = pug.compileClient('p #{name}', {
inlineRuntimeFunctions: true
});
// No external dependencies neededClient compilation integrates well with build tools:
// Gulp task
gulp.task('compile-templates', function() {
return gulp.src('./src/templates/**/*.pug')
.pipe(through2.obj(function(file, enc, callback) {
const compiled = pug.compileClient(file.contents.toString(), {
filename: file.path,
name: path.basename(file.path, '.pug') + 'Template'
});
file.contents = Buffer.from(compiled);
file.extname = '.js';
callback(null, file);
}))
.pipe(gulp.dest('./dist/templates/'));
});
// Rollup plugin
function pugPlugin() {
return {
name: 'pug',
transform(code, id) {
if (!id.endsWith('.pug')) return null;
const compiled = pug.compileClient(code, {
filename: id,
inlineRuntimeFunctions: true
});
return `export default ${compiled}`;
}
};
}Client compilation errors are similar to server-side compilation:
try {
const clientJS = pug.compileClient('invalid syntax {{}}');
} catch (err) {
console.error('Client compilation failed:', err.message);
console.error('Line:', err.line);
console.error('Filename:', err.filename);
}
// File compilation errors
try {
const clientJS = pug.compileFileClient('./missing-template.pug');
} catch (err) {
console.error('File not found:', err.code);
}Install with Tessl CLI
npx tessl i tessl/npm-pug