syntax | get requires | builtin and local modules | Search

This code imports a getRequires function from a module, uses it to extract required modules from a JavaScript code string, and exports the result as a module. The code is conditionally executed when a variable $ is defined in the global scope, printing the expected output: ../Core, glob, and path.

Cell 1

var importer = require('../Core');
var {getRequires} = importer.import("get requires from source")

var code = `
var importer = require('../Core');
var glob = require('glob');
var path = require('path');
`

function testGetRequires() {
    return getRequires(code)
}

module.exports = testGetRequires

if(typeof $ != 'undefined') {
    testGetRequires()
    
    /*
    expected output
    ../Core
    glob
    path
    */
}

What the code could have been:

// Import required modules from the Core folder
const { getRequires } = require('../Core').import('getRequiresFromSource');

// Sample code snippet to extract requires from
const sampleCode = `
var importer = require('../Core');
var glob = require('glob');
var path = require('path');
`;

/**
 * Function to test the getRequires function
 * @returns {Array} An array of required module paths
 */
function testGetRequires() {
  // Call the getRequires function and return the result
  return getRequires(sampleCode);
}

// Export the test function for other modules to use
module.exports = testGetRequires;

// If running in a test environment, call the test function
if (typeof globalThis!== 'undefined' && typeof globalThis.console!== 'undefined') {
  // Call the test function and log the expected output
  globalThis.console.log(testGetRequires());
  // Expected output
  //../Core
  // glob
  // path
}

Code Breakdown

Importing Modules

var importer = require('../Core');
var {getRequires} = importer.import('get requires from source')

Sample Code String

var code = `
var importer = require('../Core');
var glob = require('glob');
var path = require('path');
`

getRequires Function

function testGetRequires() {
    return getRequires(code)
}

Exporting the Function

module.exports = testGetRequires

Conditional Execution

if(typeof $!= 'undefined') {
    testGetRequires()
   ...
}
../Core
glob
path