• Stars
    star
    257
  • Rank 153,273 (Top 4 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Handlebars precompiler plugin for Browserify

Build Status

hbsfy

Handlebars precompiler plugin for Browserify without magic.

Compiles Handlebars templates to plain Javascript. The compiled templates only have one copy of the Handlebars runtime so they are lightweight and fast!

Usage

Install hbsfy locally to your project:

npm install --save-dev hbsfy

You will also need Handlebars installed. Handlebars 1, 2, 3, and 4 are supported for now (use 4 for best results):

npm install --save-dev handlebars

Then use it as Browserify transform module with -t:

browserify -t hbsfy main.js > bundle.js

where main.js can be like:

var template = require("./template.hbs");
document.body.innerHTML = template({ name: "Epeli" });

and template.hbs:

<h1>Hello {{name}}!</h1>

Options

Custom Extension

You can use --extensions or -e subarg option to configure custom extensions for the transform:

browserify -t [ hbsfy -e html,htm ] main.js > bundle.js

Alternate Precompiler/Compiler

You can specify how the templates are precompiled by using -p or --precompiler, which might also be used with the -c or --compiler option, like so:

browserify -t [ hbsfy -p ember-template-compiler -c Ember.Handlebars ] main.js > bundle.js

By default the precompiler is the handlebars node module and the compiler is "require('hbsfy/runtime')".

Options for the precompiler can be passed using a precompilerOptions key.

Example:

Enable myUltimateHelper only

browserify -t [ hbsfy --precompilerOptions [ --knownHelpersOnly --knownHelpers [ --myUltimateHelper ] ] ]  main.js > bundle.js

See Handlebars API reference for details.

Common JS Partial Resolution

Using the --traverse or -t option will cause partials to be resolved using node's module resolution algorithm. Be sure to prefix relative paths with ./ or ../ as needed. Otherwise the algorithm assumes a node_module is being referenced.

Example:

browserify -t [ hbsfy -t ] main.js > bundle.js
<!-- main.hbs -->
<div>{{> ./path/to/partial.hbs }}</div>
<!-- path/to/partial.hbs -->
<p>I'm a partial</p>

Inline Partials

If you are using Common JS partial resolution (setting the --traverse flag) and you are using Handlebars 4.0.0 or later, you can still use inline partials. Make sure to not use inline partial names that conflict with node_module dependencies. The inline partial will be used over a dependency reference.

package.json

Transform can be configured from the package.json too.

{
  "browserify": {
    "transform": [
      [
        "hbsfy",
        {
          "extensions": [
            "html"
          ],
          "precompilerOptions": {
            "knownHelpersOnly": true,
            "knownHelpers": {
              "myUltimateHelper": true
            }
          }
        }
      ]
    ]
  }
}

The precompiler and compiler keys are naturally available too.

See module-deps documentation for more information as this feature is implemented there (it's a part of Browserify itself).

Programmatic usage

The configure method of the transform can be used to create new transforms with different defaults.

var hbsfy = require("hbsfy").configure({
  extensions: ["html"]
});

var browserify = require("browserify");
var b = browserify("./index.js");
b.transform(hbsfy);
b.bundle().pipe(fs.createWriteStream("./bundle.js"));

Helpers

To register custom helpers, require the runtime and run registerHelper to create helper:

var Handlebars = require("hbsfy/runtime");
Handlebars.registerHelper("upcase", function(s) {
  return s.toUpperCase();
});

Partials

Partials can be created by giving precompiled template to the registerPartial function.

Handlebars.registerPartial('link', require("./partial.hbs"));

Checkout the example folder for details.

Note: if using the --traverse option, partial registration is automatic.

.compile

This synchronous method can be used to enable all hsbfy functionality in another environment, such as node or a test runner (such as mocha).

// mocha-hbs.js
var fs = require("fs");
var hbsfy = require("hbsfy");

require.extensions['.hbs'] = function (module, filename) {
  var file = fs.readFileSync(filename, "utf8");
  var opts = { traverse: true };
  return module._compile(hbsfy.compile(file, opts), filename);
}
$ mocha -r hbs:./mocha-hbs.js tests/

Remember to register your custom helpers as well! Ideally your templates themselves require your helpers and runtime, and call registerHelper. But if they don't, all helpers can be loaded at once as part of the require hook above:

// mocha-hbs.js
var fs = require("fs");
var hbsfy = require("hbsfy");
var runtime = require("hbsfy/runtime");
var helpers = require("./path/to/my/exported/helpers");

Object.keys(helpers).forEach(function (key) {
  runtime.registerHelper(key, helpers[key]);
});

require.extensions['.hbs'] = function (module, filename) {
  var file = fs.readFileSync(filename, "utf8");
  var opts = { traverse: true };
  return module._compile(hbsfy.compile(file, opts), filename);
}

Process output HTML string

This option accepts a function which takes one argument (the template file content) and returns a string which will be used as the source for the precompiled template object. The example below removes leading and trailing spaces to shorten templates.

hbsfy.configure({
  processContent: function(content) {
    content = content.replace(/^[\x20\t]+/mg, '').replace(/[\x20\t]+$/mg, '');
    content = content.replace(/^[\r\n]+/, '').replace(/[\r\n]*$/, '\n');
    return content;
  }
});

Changelog

2.8.1

  • Fix build due to source maps being included in bundle output.

2.8.0

  • Support block partials, ignoring templates with @ prefix. #60

2.7.0

  • Allow inline partials when using --traverse. #54

2.6.0

  • Add processContent option. #50

2.5.0

  • Export findPartials and compile for use in utilities / test frameworks #49.

2.4.1

2.4.0

  • support handlebars 2, 3, 4

2.3.1

  • Handle null nodes when traversing Handlebars AST.

2.3.0

  • Allow resolving / requiring partials using node's module resolution algorithm (--traverse). #47

2.2.1

  • Emit compile errors instead of crashing. #38

2.2.0

  • Support for compiler options #29

2.1.0

  • Subargs options for alternate precompilers and compilers #31

2.0.0

  • Support Browserify subargs
  • The configure method does not mutate the inner state of the module anymore
    • Instead it returns a new transform function.
  • Handlebars is not a peerDependency anymore
    • It must be manually installed
    • This relaxes completely the version binding of Handlebars - it is now possible to try Handlebars 2.0 alpha

1.3.0

  • Support Handlebars 1.3
  • Now uses the official runtime api

1.0.0

  • Remove handlebars-runtime dependency and depend directly on the handlebars module as a peer dependency.
    • Runtime must be now required with require("hbsfy/runtime") instead of require("handlebars-runtime").
    • Thanks to @kamicane for teaching me how to do this.
  • Option to configure template extensions

More Repositories

1

underscore.string

String manipulation helpers for javascript
JavaScript
3,372
star
2

react-zorm

๐Ÿชฑ Zorm - Type-safe <form> for React using Zod
TypeScript
714
star
3

immer-reducer

Type-safe and terse reducers with Typescript for React Hooks and Redux
TypeScript
225
star
4

slimux

SLIME inspired tmux integration plugin for Vim
Vim Script
216
star
5

piler

Deprecated Asset Manager for Node.js
CoffeeScript
148
star
6

redux-hooks

โš“ React Hooks implementation for Redux
TypeScript
96
star
7

node-promisepipe

Safely pipe node.js streams while capturing all errors to a single promise
JavaScript
80
star
8

requirejs-hbs

Simple Handlebars loader plugin for RequireJS
JavaScript
79
star
9

lean-redux

Redux state like local component state
JavaScript
78
star
10

angry-caching-proxy

Make package downloads lightning fast!
JavaScript
77
star
11

browserify-externalize

Create external Browserify bundles for lazy asynchronous loading
JavaScript
73
star
12

postcss-ts-classnames

PostCSS plugin to generate TypeScript types from your CSS class names.
TypeScript
70
star
13

jslibs

List of Javascript libraries
59
star
14

backbone.viewmaster

Few tested opinions on how to handle deeply nested views in Backbone.js focusing on modularity.
JavaScript
52
star
15

babel-plugin-ts-optchain

Babel plugin for transpiling legacy browser support to ts-optchain by removing Proxy usage.
TypeScript
30
star
16

trpc-cloudflare-worker

TypeScript
29
star
17

carcounter

Asynchronous module loading example with Browserify
JavaScript
24
star
18

redux-render-prop

Redux with render props. Typescript friendly.
TypeScript
22
star
19

source-map-peek

Peek into original source via source maps from the command line when devtools fail.
JavaScript
21
star
20

TextareaServer

Server for opening external text editors from Chrome
CoffeeScript
19
star
21

deno_karabiner

Write Complex Modifications for Karabiner-Elements using Typescript and Deno.
TypeScript
17
star
22

babel-plugin-display-name-custom

display name inference for your custom react component creators
JavaScript
15
star
23

geekslides

Remote controllable Node.js introduction slides
JavaScript
15
star
24

npm-release

Github action for npm (pre)releases
TypeScript
15
star
25

sauna.reload

Development & Issues MOVED to https://github.com/collective/sauna.reload
Python
13
star
26

TextareaConnect

Edit textareas in Google Chrome using any external editor!
CoffeeScript
13
star
27

node-clim

Console.Log IMproved for Node.js
JavaScript
12
star
28

react-simple

simple style only components for the web & native
JavaScript
9
star
29

typescript-redux-todoapp

Type-safe Boilerplate-free Redux Example
TypeScript
9
star
30

jquery.panfullsize

jQuery plugin for panning large images
JavaScript
8
star
31

neovim-config

Vim Script
8
star
32

Projectwatch

Watch file changes and run multiple css/js pre-processors from one watcher
JavaScript
8
star
33

multip

Tiny multi process init for containers written in Rust ๐Ÿฆ€
Rust
8
star
34

ts-box

Put exceptions into boxes ๐Ÿ“ฆ
TypeScript
8
star
35

vimconfig

Vim and other dotfiles
Vim Script
7
star
36

node-tftp

Streaming TFTP Server for node.js
JavaScript
7
star
37

react-makefile

Makefile boilerplate for React.js
JavaScript
6
star
38

yalr

YALR - Yet Another Live Reload
JavaScript
6
star
39

vscode-unsaved

Makes you actually notice when you have unsaved files
TypeScript
5
star
40

reallyexpress

Really Express extends Express with extraordinary features given by Node.js. Work in progress.
CoffeeScript
5
star
41

shell-cheatsheet

4
star
42

tmpshare

Easily share temporary files over http
JavaScript
4
star
43

ircshare

Simple service for sharing your pictures on IRC
JavaScript
3
star
44

ircshare-android

Share pictures easily in IRC from Android phone
Java
3
star
45

qdomain

Promises from domains
JavaScript
3
star
46

browserify-cs-example

Browserify v2 with CoffeeScript Source Maps
CoffeeScript
3
star
47

flysight-subtitles

Convert FlySight data files (.csv) to SubRip (.srt) subtitles.
JavaScript
3
star
48

node-handlebars-runtime

Handlebars runtime only
JavaScript
2
star
49

node-lights

Instanssi Light Server Simulator
CoffeeScript
2
star
50

revisioncask

Version control management made simple
Python
2
star
51

flips.io

JavaScript
2
star
52

subssh

Small framework for creating SSH public key based shell accounts.
Python
2
star
53

toggl-paster

I need to paste Toggl time entries into things so I made a thing.
TypeScript
2
star
54

utils

Epeli's Javascript / Typescript utilities
TypeScript
2
star
55

MAILNETD

Meta Asynchronous Irc Linked Network Email Transport Daemon
Python
1
star
56

rt

Instant tab-complete for npm scripts and Jakefiles
Rust
1
star
57

lunarvim-config

Lua
1
star
58

awesome

My Personal Awesome WM config
Lua
1
star
59

wp-graphql-todoapp

TypeScript
1
star
60

stylify

JavaScript
1
star
61

subssh_buildout

buildout for subssh development purposes
Python
1
star
62

LightManager

lightmanager tool written for instanssi.org party
Java
1
star
63

rollsum

Just experiments with rolling checksums. Nothing to see here.
C
1
star
64

sh-thunk

Generate promise returning thunks from shell strings.
JavaScript
1
star
65

konf

TypeScript
1
star
66

HAL2012

Home hack using Node.js and Raspberry Pi
CoffeeScript
1
star
67

IRCPost

Simple IRC bot with HTTP POST API
CoffeeScript
1
star
68

blog

JavaScript
1
star
69

aswyg-editor

ASWYG Editor - Also See What You Get Editor
JavaScript
1
star