Skip to content

Instantly share code, notes, and snippets.

@Sasquire
Created February 11, 2022 18:26
Show Gist options
  • Save Sasquire/d81827bf925d6d24b74744a4e489ad78 to your computer and use it in GitHub Desktop.
Save Sasquire/d81827bf925d6d24b74744a4e489ad78 to your computer and use it in GitHub Desktop.

Browserify Prepend-Text

This tool prepends a piece of text to the result of a browserify bundle. it is useful for making userscripts with browserify because the header information is a piece of text at the top of the script.

How to use

const browserify = require('browserify');
const apply_header = require('./prepend_text.js');

function bundle (header_string) {
	return browserify()
		.add(path.join('source', 'entry.js'))
		.plugin(apply_header, header_string)
		.bundle();
}

License

All code in this repository is licensed under the Unlicense and is in the Public Domain.

const stream = require('stream');
// Browserify expects the export to be a single function
module.exports = function apply_header (browserify, header) {
function create_stream () {
let first = true;
// Transform streams are both readable and writeable
// You can think of them as transforming the data that
// gets fed to it.
// (source) --write--> (Transform) --read--> (elsewhere)
return new stream.Transform({
transform (chunk, encoding, callback) {
if (first) {
first = false;
chunk = Buffer.concat([Buffer.from(header), chunk]);
}
// Writes to the internal output buffer
this.push(chunk);
callback(); // signal this chunk is done
}
});
};
function add_to_pipeline () {
// `wrap` is the last step in the browserify pipeline. It
// is for arbitrary transformations to be done at the
// end of bundling.
browserify.pipeline.get('wrap').push(create_stream());
}
browserify.on('reset', add_to_pipeline);
add_to_pipeline();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment