generate-examples-index-webpack-plugin
Version:
Generate an examples index page from your examples folder
53 lines (47 loc) • 1.37 kB
JavaScript
const fs = require('fs');
const path = require('path');
function findPackageJson() {
// try with ${cwd}/package.json
let route = path.join(process.cwd(), 'package.json');
if (fs.existsSync(route)) {
return route;
}
// try to find a package.json in the parent directories
route = path.normalize(path.join(__dirname, '..', '..', '..', '..')); // starts outside this project folder
while (route) {
const tryRoute = path.join(route, 'package.json');
if (fs.existsSync(tryRoute)) {
return tryRoute;
}
route = path.normalize(path.join(__dirname, '..'));
}
return undefined;
}
/**
* Return the package.json as an object
*
* @param {string|object} route the path of the package.json to read
* if it's an object, it will be returned directly (already read)
* if undefined, will try to find it. Returns undefined if not found
*/
function getPackageJson(route) {
// return the already provided object
if (typeof route === 'object') {
return route;
}
// try to find the path
if (!route) {
route = findPackageJson();
if (!route) {
return undefined;
}
}
// load the path
try {
const code = fs.readFileSync(route).toString();
return JSON.parse(code);
} catch (error) {
return undefined;
}
}
module.exports = getPackageJson;