or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-stringify

Browserify middleware to require() text files including templates inside client-side JavaScript files

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/stringify@5.2.x

To install, run

npx @tessl/cli install tessl/npm-stringify@5.2.0

index.mddocs/

Stringify

Stringify is a Browserify transform middleware that enables requiring text files (including HTML templates, Handlebars templates, and other text-based assets) directly inside client-side JavaScript files as strings. The package also provides Node.js integration for server-side usage and comprehensive HTML minification capabilities.

Package Information

  • Package Name: stringify
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install stringify

Core Imports

const stringify = require('stringify');

For ES modules:

import stringify from 'stringify';

Basic Usage

Browserify Transform

const browserify = require('browserify');
const stringify = require('stringify');

const bundle = browserify()
  .transform(stringify, {
    appliesTo: { includeExtensions: ['.html', '.hbs', '.txt'] }
  })
  .add('my_app_main.js');

Then in your client-side code:

const template = require('./path/to/template.html');
console.log(template); // String content of the HTML file

Node.js Require Registration

const stringify = require('stringify');

stringify.registerWithRequire({
  appliesTo: { includeExtensions: ['.txt', '.html'] },
  minify: true
});

const textFile = require('./data.txt');
console.log(textFile); // String content of the text file

Capabilities

Browserify Transform Function

Main export that handles Browserify transformations with two usage patterns: factory mode and standard mode.

/**
 * Browserify transform function with dual usage patterns
 * @param {string|object|array} file - File path (standard mode) or options (factory mode)
 * @param {object|array} options - Transform options (standard mode only)
 * @returns {Stream|Function} Transform stream (standard) or factory function
 */
function stringify(file, options);

Factory Mode (returns transform function):

  • stringify() - Uses default options
  • stringify(options) - Uses specified options

Standard Mode (returns transform stream):

  • stringify(file, options) - Transforms specific file with options

Node.js Require Registration

Registers file extensions with Node.js require system to enable requiring text files.

/**
 * Registers extensions with Node.js require to load text files as strings
 * @param {object|array} options - Configuration options for extensions and minification
 * @returns {void}
 */
function registerWithRequire(options);

Configuration Options

File Matching Configuration

The appliesTo option controls which files are processed:

interface AppliesTo {
  /** Array of file extensions to include (e.g., ['.html', '.txt']) */
  includeExtensions?: string[];
  /** Array of file extensions to exclude */
  excludeExtensions?: string[];
  /** Array of specific file paths to process */
  files?: string[];
  /** Regex pattern(s) for file matching */
  regex?: RegExp | RegExp[];
}

Transform Options

interface TransformOptions {
  /** File matching configuration */
  appliesTo?: AppliesTo;
  /** Enable HTML minification */
  minify?: boolean;
  /** File matching for minification (separate from appliesTo) */
  minifyAppliesTo?: AppliesTo;
  /** HTML minifier options */
  minifyOptions?: MinifyOptions;
}

Minification Options

interface MinifyOptions {
  /** Remove HTML comments */
  removeComments?: boolean;
  /** Remove comments from CDATA sections */
  removeCommentsFromCDATA?: boolean;
  /** Remove CDATA sections from CDATA sections */
  removeCDATASectionsFromCDATA?: boolean;
  /** Collapse whitespace */
  collapseWhitespace?: boolean;
  /** Conservative whitespace collapse */
  conservativeCollapse?: boolean;
  /** Preserve line breaks */
  preserveLineBreaks?: boolean;
  /** Collapse boolean attributes */
  collapseBooleanAttributes?: boolean;
  /** Remove attribute quotes when safe */
  removeAttributeQuotes?: boolean;
  /** Remove redundant attributes */
  removeRedundantAttributes?: boolean;
  /** Use short DOCTYPE */
  useShortDoctype?: boolean;
  /** Remove empty attributes */
  removeEmptyAttributes?: boolean;
  /** Remove script type attributes */
  removeScriptTypeAttributes?: boolean;
  /** Remove style link type attributes */
  removeStyleLinkTypeAttributes?: boolean;
  /** Remove optional tags */
  removeOptionalTags?: boolean;
  /** Remove ignored elements */
  removeIgnored?: boolean;
  /** Remove empty elements */
  removeEmptyElements?: boolean;
  /** Enable linting */
  lint?: boolean;
  /** Keep closing slash for self-closing tags */
  keepClosingSlash?: boolean;
  /** Case sensitive processing */
  caseSensitive?: boolean;
  /** Minify inline JavaScript */
  minifyJS?: boolean;
  /** Minify inline CSS */
  minifyCSS?: boolean;
  /** Minify URLs */
  minifyURLs?: boolean;
}

Test Environment Exports

Additional functions and constants are conditionally exported when NODE_ENV environment variable is set, primarily for testing and debugging purposes.

Internal Functions

/**
 * Global state object for Node.js require options
 */
const NODE_REQUIRE_OPTIONS: object;

/**
 * Internal function to handle file stringification for Node.js require
 * @param {object} module - Module object
 * @param {string} filename - File path to read and stringify
 * @returns {void}
 */
function requireStringify(module: object, filename: string): void;

/**
 * Internal string conversion function
 * @param {string} content - Content to stringify
 * @returns {string} Module export string format
 */
function stringify(content: string): string;

/**
 * Gets extensions for Node.js require registration
 * @param {object|array} options - Configuration options
 * @returns {string[]} Array of lowercase file extensions
 */
function getRequireExtensions(options?: object | array): string[];

/**
 * Normalizes user-supplied options for browserify-transform-tools
 * @param {object|array} options - User options
 * @returns {object} Normalized transform options
 */
function getTransformOptions(options?: object | array): object;

/**
 * Handles file minification logic
 * @param {string} filename - File being processed
 * @param {string} contents - File contents
 * @param {object} options - Minification options
 * @returns {string} Minified or original contents
 */
function minify(filename: string, contents: string, options: object): string;

/**
 * Determines minification configuration from user options
 * @param {object} options - User-supplied options
 * @returns {object} Minification configuration object
 */
function getMinifyOptions(options: object): object;

Configuration Constants

/**
 * Default transform options for file matching
 */
const TRANSFORM_OPTIONS: {
  includeExtensions: string[];
};

/**
 * Default minification transform options
 */
const MINIFY_TRANSFORM_OPTIONS: {
  includeExtensions: string[];
};

/**
 * Default HTML minifier options
 */
const DEFAULT_MINIFY_OPTIONS: {
  removeComments: boolean;
  removeCommentsFromCDATA: boolean;
  removeCDATASectionsFromCDATA: boolean;
  collapseWhitespace: boolean;
  conservativeCollapse: boolean;
  preserveLineBreaks: boolean;
  collapseBooleanAttributes: boolean;
  removeAttributeQuotes: boolean;
  removeRedundantAttributes: boolean;
  useShortDoctype: boolean;
  removeEmptyAttributes: boolean;
  removeScriptTypeAttributes: boolean;
  removeStyleLinkTypeAttributes: boolean;
  removeOptionalTags: boolean;
  removeIgnored: boolean;
  removeEmptyElements: boolean;
  lint: boolean;
  keepClosingSlash: boolean;
  caseSensitive: boolean;
  minifyJS: boolean;
  minifyCSS: boolean;
  minifyURLs: boolean;
};

Default File Extensions

Transform Extensions

Default extensions processed by stringify:

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

Minification Extensions

Default extensions processed by HTML minifier:

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

Usage Examples

Command Line Usage

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

Gulp Integration

const gulp = require('gulp');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const stringify = require('stringify');

gulp.task('js', function() {
  return browserify({ entries: ['src/main.js'] })
    .transform(stringify, {
      appliesTo: { includeExtensions: ['.html'] },
      minify: true
    })
    .bundle()
    .pipe(source('main.js'))
    .pipe(gulp.dest('dist'));
});

Advanced Minification Configuration

const stringify = require('stringify');

const bundle = browserify()
  .transform(stringify, {
    appliesTo: { includeExtensions: ['.html', '.hbs', '.txt'] },
    minify: true,
    minifyAppliesTo: { includeExtensions: ['.html', '.hbs'] },
    minifyOptions: {
      removeComments: true,
      collapseWhitespace: true,
      removeAttributeQuotes: true,
      minifyJS: true,
      minifyCSS: true
    }
  })
  .add('app.js');

Handlebars Template Integration

// Client-side application code
const Handlebars = require('handlebars');
const template = require('./templates/user-card.hbs');

const compiledTemplate = Handlebars.compile(template);
const html = compiledTemplate({
  name: 'John Doe',
  email: 'john@example.com'
});

document.body.innerHTML = html;

Error Handling

Common Errors

  • File Not Found: When require() references a non-existent file, stringify throws an error with the full resolved path
  • Transform Failures: Invalid configuration or file processing errors are passed through browserify-transform-tools
  • Minification Errors: Invalid HTML that cannot be minified will cause transform failures

Error Example

// This will throw: "Stringify could not find module '/absolute/path/to/missing.txt'"
const missingFile = require('./missing.txt');

Version Compatibility

  • Node.js: Requires Node.js >= 4.0.0
  • Browserify: Compatible with all standard browserify versions
  • Testing: Verified up to Node.js 8.1.3