Browserify middleware to require() text files including templates inside client-side JavaScript files
npx @tessl/cli install tessl/npm-stringify@5.2.0Stringify 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.
npm install stringifyconst stringify = require('stringify');For ES modules:
import stringify from 'stringify';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 fileconst stringify = require('stringify');
stringify.registerWithRequire({
appliesTo: { includeExtensions: ['.txt', '.html'] },
minify: true
});
const textFile = require('./data.txt');
console.log(textFile); // String content of the text fileMain 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 optionsstringify(options) - Uses specified optionsStandard Mode (returns transform stream):
stringify(file, options) - Transforms specific file with optionsRegisters 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);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[];
}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;
}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;
}Additional functions and constants are conditionally exported when NODE_ENV environment variable is set, primarily for testing and debugging purposes.
/**
* 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;/**
* 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 extensions processed by stringify:
['.html', '.htm', '.tmpl', '.tpl', '.hbs', '.text', '.txt']Default extensions processed by HTML minifier:
['.html', '.htm', '.tmpl', '.tpl', '.hbs']browserify -t [ stringify --extensions [.html .hbs] ] myfile.jsconst 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'));
});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');// 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;require() references a non-existent file, stringify throws an error with the full resolved path// This will throw: "Stringify could not find module '/absolute/path/to/missing.txt'"
const missingFile = require('./missing.txt');