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.
npm run import -- "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
}
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
var importer = require('../Core');
var {selectAst} = importer.import('select code tree')
../Core
and assigns it to the importer
variable.selectAst
from the importer
module using the import
method. The string 'select code tree'
is likely a key or identifier for the selectAst
function within the importer
module.getRequires
Functionfunction 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))
}
getRequires
function takes a single argument code
, which is likely a string representing JavaScript code.selectAst
function to extract relevant data from the code
string.selectAst
function is called with an array of two elements:
ctx
as an argument.selectAst
is made to extract the value of a Literal
node.Literal
node is found, an error is thrown with a message that includes the context object's HTML representation using htmlToTree
.selectAst
calls are concatenated and returned by the getRequires
function.getRequires
Functionmodule.exports = {
getRequires
}
getRequires
function is exported as a module, making it available for use in other parts of the application.