st-bundle
Version:
CLI for watching and bundling SpringType projects.
79 lines (78 loc) • 2.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const env_1 = require("../env");
const utils_1 = require("../utils/utils");
function stripHash(template) {
return template.replace(/([-_.]+)?\$hash([-_.]+)?/, '');
}
/**
* Writes data to the file system
* Fully detached from the context
* @param props
*/
function createWriter(props) {
let outputString = props.output ? props.output : props.isProduction ? 'dist/$hash-$name' : 'dist/$name';
// make sure it has $name in the template
if (!/\$name/.test(outputString)) {
if (/\/$/.test(outputString)) {
outputString += '$name';
}
else {
outputString += '/$name';
}
}
const outputDirectory = utils_1.ensureAbsolutePath(path.dirname(outputString), props.root || env_1.env.APP_ROOT);
let template = path.basename(outputString);
if (!props.isProduction) {
// we don't allow hashes for development for known reasons
template = stripHash(template);
}
return {
outputDirectory,
// generated template
template,
write: async (target, contents) => {
if (!path.isAbsolute(target)) {
target = path.join(outputDirectory, target);
}
await utils_1.writeFile(target, contents);
return {
target,
};
},
// generate first, then write
// this is done to simplify work when we need to know all the paths before the file is written
// in case of the sourcemaps for example
generate: (name, contents, skipHash) => {
const targetFileName = path.basename(name);
const [$name, $ext] = targetFileName.split(/(\.[a-z-0-9]+)$/);
const targetBaseDir = path.dirname(name);
const opts = {
hash: props.isProduction ? utils_1.fastHash(contents) : false,
};
let localPath = template.replace('$name', $name);
if (skipHash) {
localPath = stripHash(localPath);
}
else if (typeof opts.hash === 'string') {
localPath = localPath.replace('$hash', opts.hash);
}
localPath = path.join(targetBaseDir, `${localPath}${$ext}`);
const absPath = path.join(outputDirectory, localPath);
const relBrowserPath = utils_1.ensureFuseBoxPath(path.relative(outputDirectory, absPath));
const size = Buffer.byteLength(contents, 'utf8');
return {
size,
localPath,
absPath,
relBrowserPath,
write: async (cnt) => {
// piping the contents to webIndex instead
await utils_1.writeFile(absPath, cnt ? cnt : contents);
},
};
},
};
}
exports.createWriter = createWriter;