UNPKG

2.27 kBMarkdownView Raw
1# Stringify #
2
3Browserify plugin to require() text files (like templates) inside of your client-side JavaScript files.
4
5## Installation ##
6
7```bash
8npm install stringify
9```
10
11## Usage ##
12
13Setup Browserify to use this middleware in your app:
14
15```javascript
16var browserify = require('browserify'),
17 stringify = require('stringify');
18
19var bundle = browserify()
20 .use(stringify(['.hjs', '.html', '.whatever']))
21 .addEntry('my_app_main.js');
22
23app.use(bundle);
24```
25You might have noticed that you can pass stringify an optional array of file-extensions that you want to require() in your Browserify packages as strings. By default these are used: .html, .txt, .text, and .tmpl
26
27__NOTE__: You MUST call this as I have above. The Browserify .use() method HAS to plug this middleware in to Browserify BEFORE you add the entry point (your main client-side file) for Browserify.
28
29Now, in your clientside files you can use require() as you would for JSON and JavaScript files, but include text files that have just been parsed into a JavaScript string:
30
31```javascript
32var my_text = require('../path/to/my/text/file.txt');
33
34console.log(my_text);
35```
36
37## More Realistic Example & Use-Case ##
38
39The reason I created this was to get string versions of my Handlebars templates required in to my client-side JavaScript. You can theoretically use this for any templating parser though.
40
41Here is how that is done:
42
43application.js:
44```javascript
45var browserify = require('browserify'),
46 stringify = require('stringify');
47
48var bundle = browserify()
49 .use(stringify(['.hbs', '.handlebars']))
50 .addEntry('my_app_main.js');
51
52app.use(bundle);
53```
54
55my_app_main.js:
56```javascript
57var Handlebars = require('handlebars'),
58 template = require('my/template/path.hbs'),
59 data = require('data.json');
60
61var hbs_template = Handlebars.compile(template);
62
63// Now I can use hbs_template like I would anywhere else, passing it data and getting constructed HTML back.
64var constructed_template = hbs_template(data);
65
66/*
67 Now 'constructed_template' is ready to be appended to the DOM in the page!
68 The result of it should be:
69
70 <p>This is my string!</p>
71*/
72```
73
74my/template/path.hbs:
75```html
76<p>{{ json_data }}</p>
77```
78
79data.json
80```json
81{
82 "json_data": "This is my string!"
83}
84```