The relativeImports
function analyzes a code snippet to identify required modules, categorizing them into local, built-in, packages, and missing modules. It returns an object with arrays of these categories, using various checks and resolutions to determine the type and location of each module.
npm run import -- "builtin and local modules"
var module = require('module')
var importer = require('../Core')
var {getRequires} = importer.import("get requires")
function relativeImports(code, pathToCode) {
var result = {
local: [],
builtin: [],
packages: [],
missing: []
}
var requires = getRequires(code)
requires.forEach(imp => {
var local = imp.substr(0, 1) === '.'
try {
if(local) {
imp = path.relative(__dirname, pathToCode, imp)
require.resolve(imp)
result.local.push(imp)
} else {
if(!module.builtinModules.includes(imp)) {
throw new Error('Cannot find module')
}
result.builtin.push(imp)
}
} catch (e) {
if(!e.message.includes('Cannot find module')) {
throw e
} else {
if(local) {
result.missing.push(imp)
} else {
result.packages.push(imp)
}
}
}
})
return result
}
module.exports = {
relativeImports
}
const path = require('path');
const importer = require('../Core');
const { getRequires } = importer.import('getRequires');
/**
* Resolves relative imports in the given code and categorizes them as local, built-in, packages, or missing.
* @param {string} code - The code to analyze.
* @param {string} pathToCode - The path to the code file.
* @returns {object} An object containing the categorized imports.
*/
function relativeImports(code, pathToCode) {
const result = {
local: [],
builtin: [],
packages: [],
missing: []
};
const requires = getRequires(code);
function resolveImport(imp, category) {
try {
const relativeImp = path.relative(__dirname, pathToCode, imp);
require.resolve(relativeImp);
result.local.push(relativeImp);
} catch (e) {
if (e.message.includes('Cannot find module')) {
category === 'local'? result.missing.push(imp) : result.packages.push(imp);
} else {
throw e;
}
}
}
requires.forEach(imp => {
const local = imp.startsWith('.');
if (local) {
resolveImport(imp, 'local');
} else {
if (!module.builtinModules.includes(imp)) {
resolveImport(imp, 'package');
} else {
result.builtin.push(imp);
}
}
});
return result;
}
module.exports = { relativeImports };
The relativeImports
function analyzes a given code snippet to identify required modules. It categorizes them into local, built-in, packages, and missing modules.
code
: The code snippet to be analyzed.pathToCode
: The path to the code snippet.An object with four properties:
local
: An array of relative paths to local modules.builtin
: An array of built-in module names.packages
: An array of missing module names that are actually packages.missing
: An array of missing module names.getRequires
.path.relative
. If successful, it adds the module to the local
array.module.builtinModules
. If it does, it adds the module to the builtin
array.The relativeImports
function is exported as a module.