sammich.js
Version:
Too many JavaScript files? Put 'em in a sammich.
80 lines (65 loc) • 1.9 kB
JavaScript
class Sammich {
/**
* @type {string}
*/
#sourceCode = "";
constructor() {
this.#sourceCode = "";
}
static async bundle(moduleSourceCodes) {
const sammich = new Sammich();
for (const moduleSourceCode of moduleSourceCodes) {
await sammich.add(moduleSourceCode);
}
return sammich.toString();
}
static async bundleFiles(inputFilePaths) {
const sammich = new Sammich();
for (const inputFilePath of inputFilePaths) {
await sammich.addFile(inputFilePath);
}
return sammich.toString();
}
/**
* Add source code to the `Sammich`.
*
* @param {string} sourceCode The source code to add to the `Sammich`.
*/
add(sourceCode) {
this.#sourceCode += sourceCode + MODULE_DELIMITER;
}
/**
* Add source code from a file to the `Sammich`.
*
* @param {string} modulePath The path to the file to add to the `Sammich`.
*/
async addFile(modulePath) {
const sourceCode = await readFile(modulePath, "utf-8");
this.add(sourceCode);
}
/**
* Add source code from a file to the `Sammich`.
*
* @param {string} modulePath The path to the file to add to the `Sammich`.
*/
addFileSync(modulePath) {
const sourceCode = readFileSync(modulePath, "utf-8");
this.add(sourceCode);
}
/**
* Convert the `Sammich` to a JavaScript function.
*
* @returns {Function} The `Sammich` represented as a JavaScript function.
*/
toFunction() {
return new Function(this.toString());
}
/**
* Convert the `Sammich` to a string of JavaScript source code.
*
* @returns {string} The `Sammich` represented as a string of JavaScript source code.
*/
toString() {
return this.#sourceCode.trim();
}
}