syntax | Cell 1 | core dependencies | Search

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.

Run example

npm run import -- "builtin and local modules"

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
}

What the code could have been:

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 };

relativeImports Function

Purpose

The relativeImports function analyzes a given code snippet to identify required modules. It categorizes them into local, built-in, packages, and missing modules.

Parameters

Return Value

An object with four properties:

Logic

  1. The function extracts required modules from the code using getRequires.
  2. It iterates over the required modules and checks if they are local or built-in.
  3. For local modules, it attempts to resolve the relative path using path.relative. If successful, it adds the module to the local array.
  4. For built-in modules, it checks if the module exists in module.builtinModules. If it does, it adds the module to the builtin array.
  5. If a module is missing, it checks if the error message indicates a "Cannot find module" error. If it does, it categorizes the module as either local (if the path is relative) or a package (if the path is absolute).

Export

The relativeImports function is exported as a module.