commonjs-walker

Analyzer and tree walker for commonjs.

commonjs-walker

Analyzes and walks down the dependencies from a commonjs entry and creates a walking tree.

var walker = require('commonjs-walker');

NOTICEthat it will not walk down node_modulesand any foreign packages.

Supports:

  • require()a directory.
  • If a module is not found, commonjs-walker will attempt to load the required filename with the added extension of .js, .json, and then .node, according to File Modules
  • You can define what extensions should commonjs-walker fallback to by options.extensions, which will be very usefull for browser-side commonjs modules.

walker([options])

walker(options)
  .walk('/path/to/entry.js')
  // walk down another entry
  .walk('/path/to/entry2.js')
  // walk down many entries
  .walk(['/path/to/entry3.js', '/path/to/entry4.js'])
  .done(function(err, nodes){
      // ...
  });

Returns an EventEmitter.

Walks down from a entry point, such as package.mainof commonjs or any JavaScript file based on CommonJS, and tries to create a walker.Moduleinstance of the top level.

  • entry Paththe absolute path of the entry point.
  • nodes Objectthe hashmap of <path>: <walker.Module>

If the file structure of your project is (actually it is a very extreme scenario):

/path/to
       |-- index.js
       |-- a.png
       |-- a
           |-- index.json

index.js:

require('./a');
require('b');
var image = require.resolve('./a.png')

a/index.json

{}

Code:

walker().walk('/path/to/index.js').done(function(err, nodes){
    console.log(nodes);
});

Then, the nodesobject will be something like:

{
  '/path/to/index.js': {
    require: {
      './a': '/path/to/a/index.json',
      'b': 'b'
    },
    resolve: {
      './a.png': '/path/to/a.png'
    },
    content: <buffer>
  },
  '/path/to/a.png': {
    require: {}
  }
  '/path/to/a/index.json': {
    require: {},
    content: <buffer>
  },
  'b': {
    foreign: true
  }
}

options

All options are optional. By default, walkerworks in a very strict mode.

OptionTypeDefaultDescription
allow_cyclicBooleantruewhether should check cyclic dependencies
check_require_lengthBooleanfalsewhether should check the arguments.lengthof method require()
allow_non_literal_requireBooleantruewhether should check the usage of method require(). If false, the argument of require()must be an literal string.
comment_requireBooleantruewhether should parse @require(), @require.resolveand @require.asyncin comments.
require_resolveBooleantruewhether should analysis the usage of require.resolve().
require_asyncBooleantruewhether should record the usage of require.async().
allow_absolute_pathBooleantruewhether should allow to require an absolute path.
extensionsArray['.js', '.json', '.node']see options.extensionssection

options.extensions

type Array

When we require()a path, if pathis not found, nodejs will attempt to load the required filename with the added extension of .js, .json, and then .node. Reference via

But for browser-side environment, most usually, we do not support extension .nodewhich is what options.extensionsis for.

Especially, only tree values below are allowed:

  • ['.js']
  • ['.js', '.json'],
  • ['.js', '.json', '.node']

Frequent Options for Browsers

{
  allow_cyclic: false,
  strict_require: true,
  allow_absolute_path: false,
  extensions: ['.js', '.json']
}

.register(compiler)

.register(compilers)

Register compilers to precompile a file

  • compiler
    • compiler.testRegExp|Stringto match the given path
    • compiler.compilerfunction(content, options, callback)
      • callback function(err, result)
        • err Error=null
        • result.content Stringthe compiled content.
        • result.js Boolean=falseto indicate that if the compiled content is an javascript file.
        • result.json Boolean=falseto indicate that if the compiled content is a json file.

Events

Event: warn

  • message String

Emits if there is a warning. Warnings are potential problems that might break your code, including:

  • cyclic dependencies
  • require an absolute path

Struct: walker.Module

Actually, there is no walker.Moduleexists. We only use it to declare and describe the structure of the module.

For All types

PropertyTypeDescription
foreignBooleanwhether the current module is from a foreign package.
requireObjectThe <id>: <path>map. idis the module identifier user require()d in the module file.
resolveObject
asyncObject

Class: walker.Error

  • code Stringthe enum type of the error
  • message Stringerror messages
  • stack Stringthe origin error.stack
  • data Objectthe object of the major information of the error, this is useful for i18n.

Error codes

NOT_ALLOW_ABSOLUTE_PATH
MODULE_NOT_FOUND
CYCLIC_DEPENDENCY

Repository

https@github.com:kaelzhang/node-commonjs-walker


上一篇:jade-edge
下一篇:neuron-jade-compiler

相关推荐

  • 简单理解CommonJS规范

    写在前面: 一个文件就是一个模块。 另外本文中的示例代码需要在node.js环境中方可正常运行,否则将出现错误。事实上ES6已经出现了模块规范,如果使用ES6的模块规范是无需node.js环境的。

    2 年前
  • 理解前端模块概念:CommonJs与ES6Module

    前言 现代前端开发每时每刻都和模块打交道。例如,在项目中引入一个插件,或者实现一个供全局使用组件的JS文件。这些都可以称为模块。 在设计程序结构时,不可能把所有代码都放在一起。

    3 个月前
  • 深入 CommonJs 与 ES6 Module

    此 Github es6module example(https://github.com/Li13/module) 仓库中提供了供多种环境运行 的简单例子,可以获取代码在本地进行测试验证 ...

    1 年前
  • 教程:使用umd、commonjs和es三种模式制作自己的React 组件(库)

    创建 package.json 文件 执行命令创建 package.json 文件,一步步输入你自己的组件基本信息,下面是我创建的 初始化组件 首先在项目目录下创建相应文件夹和基本配置文...

    10 个月前
  • 批量转换 AMD 与 CommonJs 模块到 ES 模块

    就前端而言,ES6 的模块化写法已经是主流了,但很多老的项目都是用 AMD 或者 CommonJs 规范写的。 由于 Webpack 现在已经慢慢不太支持 AMD 或者 CommonJs 规范的代码,...

    10 个月前
  • 手写commonJs

    介绍 commonJs是前端模块化规范的其中一种,主要使用在node.js。 每个文件都是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。

    4 个月前
  • 实现“乞丐版”的CommonJS模块加载

    概述 有什么用? 最近看到“乞丐版”的Promise实现,所以想实现一个“乞丐版”的CommonJS规范的模块加载。希望由此: 彻底理解CommonJS规范; 为其它环境(如QuickJs)提供模块...

    6 个月前
  • 如何要求CommonJS模块在浏览器吗?

    travelboy(https://stackoverflow.com/users/534362/travelboy)提出了一个问题:How to require CommonJS modules i...

    2 年前
  • 区别“模块。出口”和“出口”的CommonJS模块系统

    CommunityXiao Peng ZenUML.com(https://stackoverflow.com/users/1/community)提出了一个问题:Difference betwee...

    2 年前
  • 前端的模块管理(RequireJS、AMD、CMD、CommonJS、ES6)

    随着应用复杂度的攀升,常规的JavaScript引入方式(script标签)已经不能满足需求,模块化管理成为团队协作的高效方法,现在的模块化管理主要有RequireJS、AMD、CMD、CommonJ...

    1 年前

官方社区

扫码加入 JavaScript 社区