Skip to content

dependents/node-ast-module-types

Repository files navigation

ast-module-types

CI npm version npm downloads

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

Usage

// 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');
  }
});

API

Each function takes a single AST node and returns a boolean.

CommonJS

  • isRequire(node): matches any require() call - plain or require.main.require()
  • isPlainRequire(node): matches a bare require() call
  • isMainScopedRequire(node): matches require.main.require()
  • isTopLevelRequire(node): takes a Program node; returns true when the first expression is a require() call
  • isAMDDriverScriptRequire(node): matches the AMD driver script form require([deps], callback)
  • isExports(node): matches module.exports or exports assignments

AMD define forms

  • isDefineAMD(node): matches any valid AMD define() call
  • isNamedForm(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) { ... })

ES modules

All types follow the ESTree spec

  • isES6Import(node): matches any ES module import form
  • isES6Export(node): matches any ES module export form
  • isDynamicImport(node): matches dynamic import() calls

License

MIT

About

AST helpers for recognizing CommonJS, AMD, and ES6 module types

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors