npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

stringify

v5.2.0

Published

Browserify middleware to be able to require() text files (including templates) inside of your client-side JavaScript files.

Downloads

169,637

Readme

Stringify

NOTE: I no longer actively maintain this package. I'd love to get PRs to keep it going though!

NPM Build Status

Browserify plugin to require() text files (such as HTML templates) inside of your client-side JavaScript files.

NOTE: Has not been tested on Node below version 4.0.0, and has been tested up to Node 8.1.3. Please report (or put a Pull Request up for) any bugs you may find.

Installation

npm install stringify

Usage

Browserify

Browserify Command Line

browserify -t [ stringify --extensions [.html .hbs] ] myfile.js

Browserify Middleware

var browserify = require('browserify'),
    stringify = require('stringify');

var bundle = browserify()
    .transform(stringify, {
      appliesTo: { includeExtensions: ['.hjs', '.html', '.whatever'] }
    })
    .add('my_app_main.js');

app.use(bundle);

NOTE: You MUST call this as I have above. The Browserify .transform() method HAS to plug this middleware in to Browserify BEFORE you add the entry point (your main client-side file) for Browserify.

Now, 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:

var my_text = require('../path/to/my/text/file.txt');

console.log(my_text);

Gulp and Browserify

To incorporate stringify into a gulp build process using browserify, register stringify as a transform as follows:

var browserify = require('browserify'),
    source = require('vinyl-source-stream'),
    stringify = require('stringify');

gulp.task('js', function() {
  return browserify({ 'entries': ['src/main.js'], 'debug' : env !== 'dev' })
    .transform(stringify, {
        appliesTo: { includeExtensions: ['.html'] },
        minify: true
    })
    .bundle()
    .pipe(source('main.js')) // gives streaming vinyl file object
    .pipe(gulp.dest(paths.build));
});

NodeJS

Allows you to "stringify" your non-JS files using the NodeJS module system. Please only use Stringify this way in NodeJS (Read: Not the browser/Browserify!)

var stringify = require('stringify');

stringify.registerWithRequire({
  appliesTo: { includeExtensions: ['.txt', '.html'] },
  minify: true,
  minifyAppliesTo: {
    includeExtensions: ['.html']
  },
  minifyOptions: {
    // html-minifier options
  }
});

var myTextFile = require('./path/to/my/text/file.txt');

console.log(myTextFile); // prints the contents of file.

For NodeJS, the appliesTo configuration option only supports the includeExtensions option - see Including / Excluding Files section for further details.

Configuration

Loading Configuration from package.json

When package.json is found, configuration is loaded by finding a key in the package.json with the name "stringify" as your transform.

{
    "name": "myProject",
    "version": "1.0.0",
    ...
    "stringify": {
        "appliesTo": { "includeExtensions": [".html"] },
        "minify": true
    }
}

Or alternatively you can set the "stringify" key to be a .js or .json file:

{
    "name": "myProject",
    "version": "1.0.0",
    ...
    "stringify": "stringifyConfig.js"
}

And then configuration will be loaded from that file:

module.exports = {
    "appliesTo": { "includeExtensions": [".html"] },
    "minify": true
};

For more details about package.json configuration, see the Browserify Transform Tools configuration documentation.

Including / Excluding Files

The configuration option appliesTo is used to configure which files should be included or excluded. The default included extensions are:

['.html', '.htm', '.tmpl', '.tpl', '.hbs', '.text', '.txt']

The appliesTo should include exactly one of the following:

| Option | Description | | ----------------------------- | ----------------------------- | | .includeExtensions | If this option is specified, then any file with an extension not in this list will skipped. | | .excludeExtensions | A list of extensions which will be skipped. | | .files | A list of paths, relative to the configuration file, of files which should be transformed. Only these files will be transformed. | | .regex | A regex or a list of regexes. If any regex matches the full path of the file, then the file will be processed, otherwise not. |

For more details about the appliesTo configuration property, see the Browserify Transform Tools configuration documentation.

Minification

By default, files will not get minified - setting minify configuration option to true will enable this.

The minifyAppliesTo configuration option allows files to be included or excluded from the minifier in a similar way to appliesTo (see Including / Excluding Files section for more details).

The default included file extensions are:

['.html', '.htm', '.tmpl', '.tpl', '.hbs']

The options set in the minifyOptions configuration option are passed through to html-minifier (for more informations or to override those options, please go to html-minifier github).

The default value of minifyOptions is:

{
  removeComments: true,
  removeCommentsFromCDATA: true,
  removeCDATASectionsFromCDATA: true,
  collapseWhitespace: true,
  conservativeCollapse: false,
  preserveLineBreaks: false,
  collapseBooleanAttributes: false,
  removeAttributeQuotes: true,
  removeRedundantAttributes: false,
  useShortDoctype: false,
  removeEmptyAttributes: false,
  removeScriptTypeAttributes: false,
  removeStyleLinkTypeAttributes: false,
  removeOptionalTags: false,
  removeIgnored: false,
  removeEmptyElements: false,
  lint: false,
  keepClosingSlash: false,
  caseSensitive: false,
  minifyJS: false,
  minifyCSS: false,
  minifyURLs: false
}

If you require an HTML file and you want to minify the requested string, you can configure Stringify to do it:

stringify({
  appliesTo: { includeExtensions: ['.txt', '.html'] },
  minify: true,
  minifyAppliesTo: {
    includeExtensions: ['.html']
  },
  minifyOptions: {
    // html-minifier options
  }
})

Realistic Example/Use-Case

The 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.

Here is how that is done:

application.js:

var browserify = require('browserify'),
    stringify = require('stringify');

var bundle = browserify()
    .transform(stringify, {
      appliesTo: { includeExtensions: ['.hbs', '.handlebars'] }
    })
    .addEntry('my_app_main.js');

app.use(bundle);

my_app_main.js:

var Handlebars = require('handlebars'),
    template = require('my/template/path.hbs'),
    data = {
      "json_data": "This is my string!"
    };

var hbs_template = Handlebars.compile(template);

// Now I can use hbs_template like I would anywhere else, passing it data and getting constructed HTML back.
var constructed_template = hbs_template(data);

/*
  Now 'constructed_template' is ready to be appended to the DOM in the page!
  The result of it should be:

  <p>This is my string!</p>
*/

my/template/path.hbs:

<p>{{ json_data }}</p>

Contributing

If you would like to contribute code, please do the following:

  1. Fork this repository and make your changes.
  2. Write tests for any new functionality. If you are fixing a bug that tests did not cover, please make a test that reproduces the bug.
  3. Add your name to the "contributors" section in the package.json file.
  4. Squash all of your commits into a single commit via git rebase -i.
  5. Run the tests by running npm install && make test from the source directory.
  6. Assuming those pass, send the Pull Request off to me for review!

Please do not iterate the package.json version number – I will do that myself when I publish it to NPM.

Style-Guide

Please follow this simple style-guide for all code contributions:

  • Indent using spaces.
  • camelCase all callables.
  • Use semi-colons.
  • Place a space after a conditional or function name, and its conditions/arguments. function (...) {...}