Skip to content

Instantly share code, notes, and snippets.

@pax-k
Last active May 30, 2023 07:54
Show Gist options
  • Save pax-k/ffd9372cb057ac2ced0ad183f9e861b8 to your computer and use it in GitHub Desktop.
Save pax-k/ffd9372cb057ac2ced0ad183f9e861b8 to your computer and use it in GitHub Desktop.
const fs = require("fs");
const path = require("path");
const readJson = require("read-package-json");
const readPkgJson = (path) => {
return new Promise((resolve, reject) => {
readJson(path, console.error, false, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
const checkDependencies = async (dir) => {
const packageJsonPath = path.join(dir, "package.json");
const nodeModulesPath = path.join(dir, "node_modules");
const packageJson = await readPkgJson(packageJsonPath);
const deps = [...Object.keys(packageJson.dependencies || {})];
const browserOnly = [];
const nodeAndBrowser = [];
const nodeOnly = [];
for (const dep of deps) {
const depPackageJsonPath = path.join(nodeModulesPath, dep, "package.json");
if (!fs.existsSync(depPackageJsonPath)) {
console.error(`Cannot find module '${dep}' in node_modules.`);
continue;
}
const depPackageJson = await readPkgJson(depPackageJsonPath);
if (
(depPackageJson.browser && depPackageJson.main) ||
depPackageJson.module
) {
nodeAndBrowser.push(dep);
} else if (depPackageJson.browser && !depPackageJson.main) {
browserOnly.push(dep);
} else if (
depPackageJson.main ||
(depPackageJson.engines && !depPackageJson.browser)
) {
nodeOnly.push(dep);
}
}
return {
browserOnly,
nodeAndBrowser,
nodeOnly,
};
};
checkDependencies(".")
.then((result) => {
console.log("Browser only:", result.browserOnly);
console.log("Node.js and Browser:", result.nodeAndBrowser);
console.log("Node.js only:", result.nodeOnly);
})
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment