• Stars
    star
    209
  • Rank 181,332 (Top 4 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

walk the dependency graph to generate a stream of json output

module-deps

walk the dependency graph to generate json output that can be fed into browser-pack

build status

example

var mdeps = require('module-deps');
var JSONStream = require('JSONStream');

var md = mdeps();
md.pipe(JSONStream.stringify()).pipe(process.stdout);
md.end({ file: __dirname + '/files/main.js' });

output:

$ node example/deps.js
[
{"id":"/home/substack/projects/module-deps/example/files/main.js","source":"var foo = require('./foo');\nconsole.log('main: ' + foo(5));\n","entry":true,"deps":{"./foo":"/home/substack/projects/module-deps/example/files/foo.js"}}
,
{"id":"/home/substack/projects/module-deps/example/files/foo.js","source":"var bar = require('./bar');\n\nmodule.exports = function (n) {\n    return n * 111 + bar(n);\n};\n","deps":{"./bar":"/home/substack/projects/module-deps/example/files/bar.js"}}
,
{"id":"/home/substack/projects/module-deps/example/files/bar.js","source":"module.exports = function (n) {\n    return n * 100;\n};\n","deps":{}}
]

and you can feed this json data into browser-pack:

$ node example/deps.js | browser-pack | node
main: 1055

usage

usage: module-deps [files]

  generate json output from each entry file

methods

var mdeps = require('module-deps')

var d = mdeps(opts={})

Return an object transform stream d that expects entry filenames or { id: ..., file: ... } objects as input and produces objects for every dependency from a recursive module traversal as output.

Each file in files can be a string filename or a stream.

Optionally pass in some opts:

  • opts.transform - a string or array of string transforms (see below)

  • opts.transformKey - an array path of strings showing where to look in the package.json for source transformations. If falsy, don't look at the package.json at all.

  • opts.resolve - custom resolve function using the opts.resolve(id, parent, cb) signature that browser-resolve has

  • opts.detect - a custom dependency detection function. opts.detect(source) should return an array of dependency module names. By default detective is used.

  • opts.filter - a function (id) to skip resolution of some module id strings. If defined, opts.filter(id) should return truthy for all the ids to include and falsey for all the ids to skip.

  • opts.postFilter - a function (id, file, pkg) that gets called after id has been resolved. Return false to skip this file.

  • opts.packageFilter - transform the parsed package.json contents before using the values. opts.packageFilter(pkg, dir) should return the new pkg object to use.

  • opts.noParse - an array of absolute paths to not parse for dependencies. Use this for large dependencies like jquery or threejs which take forever to parse.

  • opts.cache - an object mapping filenames to file objects to skip costly io

  • opts.packageCache - an object mapping filenames to their parent package.json contents for browser fields, main entries, and transforms

  • opts.fileCache - an object mapping filenames to raw source to avoid reading from disk.

  • opts.persistentCache - a complex cache handler that allows async and persistent caching of data. A persistentCache needs to follow this interface:

    function persistentCache (
        file, // the path to the file that is loaded
        id,   // the id that is used to reference this file
        pkg,  // the package that this file belongs to fallback
        fallback, // async fallback handler to be called if the cache doesn't hold the given file 
        cb    // callback handler that receives the cache data
    ) {
        if (hasError()) {
            return cb(error) // Pass any error to the callback
        }
    
        var fileData = fs.readFileSync(file)
        var key = keyFromFile(file, fileData)
    
        if (db.has(key)) {
            return cb(null, {
                source: db.get(key).toString(),
                package: pkg, // The package for housekeeping
                deps: {
                    'id':  // id that is used to reference a required file
                    'file' // file path to the required file
                }
            })
        }
        //
        // The fallback will process the file in case the file is not
        // in cache.
        //
        // Note that if your implementation doesn't need the file data
        // then you can pass `null` instead of the source and the fallback will
        // fetch the data by itself.
        //
        fallback(fileData, function (error, cacheableEntry) {
            if (error) {
                return cb(error)
            }
            db.addToCache(key, cacheableEntry)
            cb(null, cacheableEntry)
        })
    }
  • opts.paths - array of global paths to search. Defaults to splitting on ':' in process.env.NODE_PATH

  • opts.ignoreMissing - ignore files that failed to resolve

input objects

Input objects should be string filenames or objects with these parameters:

  • row.file - filename
  • row.entry - whether to treat this file as an entry point, defaults to true. Set to false to include this file, but not run it automatically.
  • row.expose - name to be exposed as
  • row.noparse - when true, don't parse the file contents for dependencies

or objects can specify transforms:

  • row.transform - string name, path, or function
  • row.options - transform options as an object
  • row.global - boolean, whether the transform is global

output objects

Output objects describe files with dependencies. They have these properties:

  • row.id - an identifier for the file, used in the row.deps prperty
  • row.file - path to the source file
  • row.entry - true if the file is an entry point
  • row.expose - name to be exposed as
  • row.source - source file content as a string
  • row.deps - object describing dependencies. The keys are strings as used in require() calls in the file, and values are the row IDs (file paths) of dependencies.

events

d.on('transform', function (tr, file) {})

Every time a transform is applied to a file, a 'transform' event fires with the instantiated transform stream tr.

d.on('file', function (file) {})

Every time a file is read, this event fires with the file path.

d.on('missing', function (id, parent) {})

When opts.ignoreMissing is enabled, this event fires for each missing package.

d.on('package', function (pkg) {})

Every time a package is read, this event fires. The directory name of the package is available in pkg.__dirname.

transforms

module-deps can be configured to run source transformations on files before parsing them for require() calls. These transforms are useful if you want to compile a language like coffeescript on the fly or if you want to load static assets into your bundle by parsing the AST for fs.readFileSync() calls.

If the transform is a function, it should take the file name as an argument and return a through stream that will be written file contents and should output the new transformed file contents.

If the transform is a string, it is treated as a module name that will resolve to a module that is expected to follow this format:

var through = require('through2');
module.exports = function (file, opts) { return through() };

You don't necessarily need to use the through2 module to create a readable/writable filter stream for transforming file contents, but this is an easy way to do it.

module-deps looks for require() calls and adds their arguments as dependencies of a file. Transform streams can emit 'dep' events to include additional dependencies that are not consumed with require().

When you call mdeps() with an opts.transform, the transformations you specify will not be run for any files in node_modules/. This is because modules you include should be self-contained and not need to worry about guarding themselves against transformations that may happen upstream.

Modules can apply their own transformations by setting a transformation pipeline in their package.json at the opts.transformKey path. These transformations only apply to the files directly in the module itself, not to the module's dependants nor to its dependencies.

package.json transformKey

Transform keys live at a configurable location in the package.json denoted by the opts.transformKey array.

For a transformKey of ['foo','bar'], the transformKey can be a single string ("fff"):

{
  "foo": {
    "bar": "fff"
  }
}

or an array of strings (["fff","ggg"]):

{
  "foo": {
    "bar": ["fff","ggg"]
  }
}

If you want to pass options to the transforms, you can use a 2-element array inside of the primary array. Here fff gets an options object with {"x":3} and ggg gets {"y":4}:

{
  "foo": {
    "bar": [["fff",{"x":3}],["ggg",{"y":4}]]
  }
}

Options sent to the module-deps constructor are also provided under opts._flags. These options are sometimes required if your transform needs to do something different when browserify is run in debug mode, for example.

usage

module-deps [FILES] OPTIONS

  Generate json output for the entry point FILES.

OPTIONS are:

  -t TRANSFORM  Apply a TRANSFORM.
  -g TRANSFORM  Apply a global TRANSFORM.

install

With npm, to get the module do:

npm install module-deps

and to get the module-deps command do:

npm install -g module-deps

license

MIT

More Repositories

1

browserify

browser-side require() the node.js way
JavaScript
14,500
star
2

browserify-handbook

how to build modular applications with browserify
JavaScript
4,574
star
3

watchify

watch mode for browserify builds
JavaScript
1,783
star
4

events

Node's event emitter for all engines.
JavaScript
1,351
star
5

resolve

Implements the node.js require.resolve() algorithm
JavaScript
765
star
6

crypto-browserify

partial implementation of node's `crypto` for the browser
JavaScript
641
star
7

wzrd.in

browserify as a service.
JavaScript
633
star
8

browserify-website

the code that runs http://browserify.org
HTML
590
star
9

brfs

browserify fs.readFileSync() static asset inliner
JavaScript
559
star
10

rustify

Rust WebAssembly transform for Browserify
JavaScript
494
star
11

webworkify

launch a web worker that can require() in the browser with browserify
JavaScript
412
star
12

tinyify

a browserify plugin that runs various optimizations, so you don't have to install them all manually. makes your bundles tiny!
JavaScript
409
star
13

detective

Find all calls to require() no matter how deeply nested using a proper walk of the AST
JavaScript
409
star
14

factor-bundle

factor browser-pack bundles into common shared bundles
JavaScript
402
star
15

commonjs-assert

Node.js's require('assert') for all engines
JavaScript
292
star
16

sha.js

Streamable SHA hashes in pure javascript
JavaScript
285
star
17

http-browserify

node's http module, but for the browser
JavaScript
243
star
18

node-util

node.js util module as a module
JavaScript
239
star
19

bundle-collapser

convert bundle paths to IDs to save bytes in browserify bundles
JavaScript
194
star
20

vm-browserify

require('vm') like in node but for the browser
JavaScript
189
star
21

pbkdf2

PBKDF2 with any supported hashing algorithm in Node
JavaScript
184
star
22

browser-pack

pack node-style source files from a json stream into a browser bundle
JavaScript
173
star
23

static-eval

evaluate statically-analyzable expressions
JavaScript
169
star
24

path-browserify

The path module from Node.js for browsers
JavaScript
154
star
25

common-shakeify

browserify tree shaking plugin using `common-shake`
JavaScript
105
star
26

browser-resolve

resolve function which support the browser field in package.json
JavaScript
99
star
27

stream-browserify

the stream module from node core for browsers
JavaScript
98
star
28

randombytes

random bytes from browserify stand alone
JavaScript
94
star
29

diffie-hellman

pure js diffie-hellman
JavaScript
89
star
30

awesome-browserify

🔮 A curated list of awesome Browserify resources, libraries, and tools.
86
star
31

syntax-error

detect and report syntax errors in source code strings
JavaScript
78
star
32

static-module

convert module usage to inline expressions
JavaScript
73
star
33

ify-loader

Webpack loader to handle browserify transforms as intended.
JavaScript
67
star
34

browserify-aes

aes, for browserify
JavaScript
61
star
35

createHmac

Node style HMAC for use in the browser, with native implementation in node
JavaScript
61
star
36

stream-splicer

streaming pipeline with a mutable configuration
JavaScript
55
star
37

browser-unpack

parse a bundle generated by browser-pack
JavaScript
54
star
38

browserify-zlib

Full zlib module for browserify
JavaScript
54
star
39

createHash

Node style hashes for use in the browser, with native hash functions in node
JavaScript
52
star
40

md5.js

node style md5 on pure JavaScript
JavaScript
41
star
41

labeled-stream-splicer

stream splicer with labels
JavaScript
39
star
42

browserify-sign

createSign and createVerify in your browser
JavaScript
37
star
43

ripemd160

JavaScript component to compute the RIPEMD160 hash of strings or bytes.
JavaScript
32
star
44

console-browserify

Emulate console for all the browsers
JavaScript
31
star
45

publicEncrypt

publicEncrypt/privateDecrypt for browserify
JavaScript
29
star
46

buffer-xor

A simple module for bitwise-xor on buffers
JavaScript
29
star
47

insert-module-globals

insert implicit module globals into a module-deps stream
JavaScript
26
star
48

createECDH

browserify version of crypto.createECDH
JavaScript
24
star
49

timers-browserify

timers module for browserify
JavaScript
23
star
50

EVP_BytesToKey

JavaScript
20
star
51

parse-asn1

JavaScript
19
star
52

browserify-rsa

JavaScript
19
star
53

cipher-base

abstract base class for crypto-streams
JavaScript
18
star
54

browserify-cipher

JavaScript
18
star
55

deps-sort

sort module-deps output for deterministic browserify bundles
JavaScript
16
star
56

tty-browserify

the tty module from node core for browsers
JavaScript
14
star
57

acorn-node

the acorn javascript parser, preloaded with plugins for syntax parity with recent node versions
JavaScript
12
star
58

hash-base

abstract base class for hash-streams
JavaScript
11
star
59

admin

administrative procedures for the browserify org
11
star
60

discuss

discuss project organization, initiatives, and whatever!
11
star
61

browserify-des

DES for browserify
JavaScript
10
star
62

randomfill

JavaScript
9
star
63

buffer-reverse

A lite module for byte reversal on buffers.
JavaScript
6
star
64

hash-test-vectors

JavaScript
3
star
65

pseudorandombytes

pseudorandombytes for the browser
JavaScript
3
star
66

detective-esm

find es module dependencies [experimental]
JavaScript
2
star
67

timing-safe-equal

JavaScript
2
star
68

perf-hooks-browserify

[WIP] The perf_hooks node module API for browserify
JavaScript
2
star
69

.github

Housing of Browserify's GitHub configuration and base files
1
star
70

scrypt

JavaScript
1
star