zarbis
Version:
Configuration-less build tool
89 lines • 3.17 kB
JavaScript
import * as path from 'path';
import { readFile } from 'fs/promises';
const PLUGIN_NAME = 'PackageJsonGenerator';
export default class PackageJsonGenerator {
otherPackageValues = {};
projectDir;
constructor(otherPackageValues = {}, projectDir) {
this.otherPackageValues = otherPackageValues;
this.projectDir = projectDir;
}
apply(compiler) {
compiler.hooks.emit.tapAsync(PLUGIN_NAME, async (compilation, callback) => {
let dependencies = {};
try {
dependencies = orderKeys(JSON.parse((await readFile(path.join(this.projectDir, 'package.json'))).toString()).dependencies);
}
catch (e) { }
const other = process.env.ADDITIONAL_PACKAGE_JSONS;
if (other)
for (let json of other.split(';')) {
const deps = orderKeys(JSON.parse((await readFile(path.join(this.projectDir, json))).toString()).dependencies);
dependencies = { ...dependencies, ...deps };
}
const files = compilation.entrypoints.get('main').chunks.map(c => [...c.files]).flat();
const packageJson = {
...this.otherPackageValues,
dependencies,
main: 'index.js',
scripts: {
start: 'node index.js'
}
};
const json = JSON.stringify(packageJson, null, 4);
const index = `module.exports=require('./${files[0]}');${files.slice(1).map(e => `require('./${e}')`).join(';')}`;
compilation.assets['index.js'] = {
source() {
return index;
},
size() {
return index.length;
}
};
for (let lockFileName of ['yarn.lock', 'package-lock.json']) {
try {
const lockJSON = (await readFile(path.join(this.projectDir, lockFileName))).toString();
compilation.assets[lockFileName] = {
source() {
return lockJSON;
},
size() {
return lockJSON.length;
}
};
}
catch (e) { }
}
compilation.assets['package.json'] = {
source() {
return json;
},
size() {
return json.length;
}
};
callback();
});
}
}
function orderKeys(obj) {
const keys = Object.keys(obj).sort(function keyOrder(k1, k2) {
if (k1 < k2)
return -1;
else if (k1 > k2)
return +1;
else
return 0;
});
let i;
let after = {};
for (i = 0; i < keys.length; i++) {
after[keys[i]] = obj[keys[i]];
delete obj[keys[i]];
}
for (i = 0; i < keys.length; i++) {
obj[keys[i]] = after[keys[i]];
}
return obj;
}
//# sourceMappingURL=packageJsonGenerator.js.map