syntax | | Cell 1 | Search

The code imports dependencies, including a selectAst function, and uses it to define a getRequires function that extracts require statements from JavaScript code. The getRequires function is then exported as a module, making it available for use in other parts of the application.

Run example

npm run import -- "get requires"

get requires

var importer = require('../Core');
var {selectAst} = importer.import("select code tree")

// TODO: use this in files and gulp script 
//   require("module").builtinModules
function getRequires(code) {
    return [].concat.apply([], selectAst([
        `//CallExpression[./Identifier[@name="require"]]`,
        (ctx) => {
            var req = selectAst([`.//Literal/@value`], ctx)
            if(req.length === 0) throw new Error(
                `dynamic require: ${JSON.stringify(htmlToTree(ctx))}`)
            return req;
        }
    ], code))
}


module.exports = {
    getRequires
}

What the code could have been:

const { selectAst } = require('../Core');

/**
 * Extracts the require statements from the given code.
 * 
 * @param {string} code The code to extract require statements from.
 * @returns {string[]} An array of require statements.
 */
function getRequires(code) {
    const requires = selectAst([
        'CallExpression[./Identifier[@name="require"]]',
        (ctx) => {
            const values = selectAst(['./Literal[@value]', './TemplateLiteral[@value]'], ctx);
            if (values.length === 0) {
                throw new Error(`Dynamic require: ${JSON.stringify(selectAst(['//code'], ctx))}`);
            }
            return values;
        }
    ], code);

    // Remove duplicates and empty values
    return requires.filter((require, index, self) => {
        return self.indexOf(require) === index && require.trim()!== '';
    });
}

module.exports = { getRequires };

Code Breakdown

Importing Dependencies

var importer = require('../Core');
var {selectAst} = importer.import('select code tree')

Defining the getRequires Function

function getRequires(code) {
    return [].concat.apply([], selectAst([
        `//CallExpression[./Identifier[@name="require"]]`,
        (ctx) => {
            var req = selectAst([`.//Literal/@value`], ctx)
            if(req.length === 0) throw new Error(
                `dynamic require: ${JSON.stringify(htmlToTree(ctx))}`)
            return req;
        }
    ], code))
}

Exporting the getRequires Function

module.exports = {
    getRequires
}