A collection of useful helper functions when trying to determine module type (CommonJS or AMD) properties of an AST node.
AST checks are based on the Esprima (Spidermonkey) format
npm install ast-module-types// ESM
import { isRequire } from 'ast-module-types';
// CommonJS
const { isRequire } = require('ast-module-types');The functions take a single AST node and return a boolean. To get nodes, walk the AST with a tool like node-source-walk:
import { isRequire } from 'ast-module-types';
import Walker from 'node-source-walk';
const walker = new Walker();
walker.walk('const x = require("lodash")', node => {
if (isRequire(node)) {
console.log('found require call');
}
});Each function takes a single AST node and returns a boolean.
isRequire(node): matches anyrequire()call - plain orrequire.main.require()isPlainRequire(node): matches a barerequire()callisMainScopedRequire(node): matchesrequire.main.require()isTopLevelRequire(node): takes aProgramnode; returns true when the first expression is arequire()callisAMDDriverScriptRequire(node): matches the AMD driver script formrequire([deps], callback)isExports(node): matchesmodule.exportsorexportsassignments
isDefineAMD(node): matches any valid AMDdefine()callisNamedForm(node):define('name', [deps], factory)isDependencyForm(node):define([deps], factory)isFactoryForm(node):define(function(require) { ... })isNoDependencyForm(node):define({})isREMForm(node):define(function(require, exports, module) { ... })
All types follow the ESTree spec
isES6Import(node): matches any ES module import formisES6Export(node): matches any ES module export formisDynamicImport(node): matches dynamicimport()calls