GithubHelp home page GithubHelp logo

browserify / browser-resolve Goto Github PK

View Code? Open in Web Editor NEW
101.0 101.0 70.0 146 KB

resolve function which support the browser field in package.json

License: MIT License

JavaScript 99.96% CoffeeScript 0.04%

browser-resolve's Introduction

browserify

require('modules') in the browser

Use a node-style require() to organize your browser code and load modules installed by npm.

browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single <script> tag.

build status

browserify!

getting started

If you're new to browserify, check out the browserify handbook and the resources on browserify.org.

example

Whip up a file, main.js with some require()s in it. You can use relative paths like './foo.js' and '../lib/bar.js' or module paths like 'gamma' that will search node_modules/ using node's module lookup algorithm.

var foo = require('./foo.js');
var bar = require('../lib/bar.js');
var gamma = require('gamma');

var elem = document.getElementById('result');
var x = foo(100) + bar('baz');
elem.textContent = gamma(x);

Export functionality by assigning onto module.exports or exports:

module.exports = function (n) { return n * 111 }

Now just use the browserify command to build a bundle starting at main.js:

$ browserify main.js > bundle.js

All of the modules that main.js needs are included in the bundle.js from a recursive walk of the require() graph using required.

To use this bundle, just toss a <script src="bundle.js"></script> into your html!

install

With npm do:

npm install browserify

usage

Usage: browserify [entry files] {OPTIONS}

Standard Options:

    --outfile, -o  Write the browserify bundle to this file.
                   If unspecified, browserify prints to stdout.

    --require, -r  A module name or file to bundle.require()
                   Optionally use a colon separator to set the target.

      --entry, -e  An entry point of your app

     --ignore, -i  Replace a file with an empty stub. Files can be globs.

    --exclude, -u  Omit a file from the output bundle. Files can be globs.

   --external, -x  Reference a file from another bundle. Files can be globs.

  --transform, -t  Use a transform module on top-level files.

    --command, -c  Use a transform command on top-level files.

  --standalone -s  Generate a UMD bundle for the supplied export name.
                   This bundle works with other module systems and sets the name
                   given as a window global if no module system is found.

       --debug -d  Enable source maps that allow you to debug your files
                   separately.

       --help, -h  Show this message

For advanced options, type `browserify --help advanced`.

Specify a parameter.
Advanced Options:

  --insert-globals, --ig, --fast    [default: false]

    Skip detection and always insert definitions for process, global,
    __filename, and __dirname.

    benefit: faster builds
    cost: extra bytes

  --insert-global-vars, --igv

    Comma-separated list of global variables to detect and define.
    Default: __filename,__dirname,process,Buffer,global

  --detect-globals, --dg            [default: true]

    Detect the presence of process, global, __filename, and __dirname and define
    these values when present.

    benefit: npm modules more likely to work
    cost: slower builds

  --ignore-missing, --im            [default: false]

    Ignore `require()` statements that don't resolve to anything.

  --noparse=FILE

    Don't parse FILE at all. This will make bundling much, much faster for giant
    libs like jquery or threejs.

  --no-builtins

    Turn off builtins. This is handy when you want to run a bundle in node which
    provides the core builtins.

  --no-commondir

    Turn off setting a commondir. This is useful if you want to preserve the
    original paths that a bundle was generated with.

  --no-bundle-external

    Turn off bundling of all external modules. This is useful if you only want
    to bundle your local files.

  --bare

    Alias for both --no-builtins, --no-commondir, and sets --insert-global-vars
    to just "__filename,__dirname". This is handy if you want to run bundles in
    node.

  --no-browser-field, --no-bf

    Turn off package.json browser field resolution. This is also handy if you
    need to run a bundle in node.

  --transform-key

    Instead of the default package.json#browserify#transform field to list
    all transforms to apply when running browserify, a custom field, like, e.g.
    package.json#browserify#production or package.json#browserify#staging
    can be used, by for example running:
    * `browserify index.js --transform-key=production > bundle.js`
    * `browserify index.js --transform-key=staging > bundle.js`

  --node

    Alias for --bare and --no-browser-field.

  --full-paths

    Turn off converting module ids into numerical indexes. This is useful for
    preserving the original paths that a bundle was generated with.

  --deps

    Instead of standard bundle output, print the dependency array generated by
    module-deps.

  --no-dedupe

    Turn off deduping.

  --list

    Print each file in the dependency graph. Useful for makefiles.

  --extension=EXTENSION

    Consider files with specified EXTENSION as modules, this option can used
    multiple times.

  --global-transform=MODULE, -g MODULE

    Use a transform module on all files after any ordinary transforms have run.

  --ignore-transform=MODULE, -it MODULE

    Do not run certain transformations, even if specified elsewhere.

  --plugin=MODULE, -p MODULE

    Register MODULE as a plugin.

Passing arguments to transforms and plugins:

  For -t, -g, and -p, you may use subarg syntax to pass options to the
  transforms or plugin function as the second parameter. For example:

    -t [ foo -x 3 --beep ]

  will call the `foo` transform for each applicable file by calling:

    foo(file, { x: 3, beep: true })

compatibility

Many npm modules that don't do IO will just work after being browserified. Others take more work.

Many node built-in modules have been wrapped to work in the browser, but only when you explicitly require() or use their functionality.

When you require() any of these modules, you will get a browser-specific shim:

Additionally, if you use any of these variables, they will be defined in the bundled output in a browser-appropriate way:

  • process
  • Buffer
  • global - top-level scope object (window)
  • __filename - file path of the currently executing file
  • __dirname - directory path of the currently executing file

more examples

external requires

You can just as easily create a bundle that will export a require() function so you can require() modules from another script tag. Here we'll create a bundle.js with the through and duplexer modules.

$ browserify -r through -r duplexer -r ./my-file.js:my-module > bundle.js

Then in your page you can do:

<script src="bundle.js"></script>
<script>
  var through = require('through');
  var duplexer = require('duplexer');
  var myModule = require('my-module');
  /* ... */
</script>

external source maps

If you prefer the source maps be saved to a separate .js.map source map file, you may use exorcist in order to achieve that. It's as simple as:

$ browserify main.js --debug | exorcist bundle.js.map > bundle.js

Learn about additional options here.

multiple bundles

If browserify finds a required function already defined in the page scope, it will fall back to that function if it didn't find any matches in its own set of bundled modules.

In this way, you can use browserify to split up bundles among multiple pages to get the benefit of caching for shared, infrequently-changing modules, while still being able to use require(). Just use a combination of --external and --require to factor out common dependencies.

For example, if a website with 2 pages, beep.js:

var robot = require('./robot.js');
console.log(robot('beep'));

and boop.js:

var robot = require('./robot.js');
console.log(robot('boop'));

both depend on robot.js:

module.exports = function (s) { return s.toUpperCase() + '!' };
$ browserify -r ./robot.js > static/common.js
$ browserify -x ./robot.js beep.js > static/beep.js
$ browserify -x ./robot.js boop.js > static/boop.js

Then on the beep page you can have:

<script src="common.js"></script>
<script src="beep.js"></script>

while the boop page can have:

<script src="common.js"></script>
<script src="boop.js"></script>

This approach using -r and -x works fine for a small number of split assets, but there are plugins for automatically factoring out components which are described in the partitioning section of the browserify handbook.

api example

You can use the API directly too:

var browserify = require('browserify');
var b = browserify();
b.add('./browser/main.js');
b.bundle().pipe(process.stdout);

methods

var browserify = require('browserify')

browserify([files] [, opts])

Returns a new browserify instance.

files
String, file object, or array of those types (they may be mixed) specifying entry file(s).
opts
Object.

files and opts are both optional, but must be in the order shown if both are passed.

Entry files may be passed in files and / or opts.entries.

External requires may be specified in opts.require, accepting the same formats that the files argument does.

If an entry file is a stream, its contents will be used. You should pass opts.basedir when using streaming files so that relative requires can be resolved.

opts.entries has the same definition as files.

opts.noParse is an array which will skip all require() and global parsing for each file in the array. Use this for giant libs like jquery or threejs that don't have any requires or node-style globals but take forever to parse.

opts.transform is an array of transform functions or modules names which will transform the source code before the parsing.

opts.ignoreTransform is an array of transformations that will not be run, even if specified elsewhere.

opts.plugin is an array of plugin functions or module names to use. See the plugins section below for details.

opts.extensions is an array of optional extra extensions for the module lookup machinery to use when the extension has not been specified. By default browserify considers only .js and .json files in such cases.

opts.basedir is the directory that browserify starts bundling from for filenames that start with ..

opts.paths is an array of directories that browserify searches when looking for modules which are not referenced using relative path. Can be absolute or relative to basedir. Equivalent of setting NODE_PATH environmental variable when calling browserify command.

opts.commondir sets the algorithm used to parse out the common paths. Use false to turn this off, otherwise it uses the commondir module.

opts.fullPaths disables converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with.

opts.builtins sets the list of built-ins to use, which by default is set in lib/builtins.js in this distribution.

opts.bundleExternal boolean option to set if external modules should be bundled. Defaults to true.

When opts.browserField is false, the package.json browser field will be ignored. When opts.browserField is set to a string, then a custom field name can be used instead of the default "browser" field.

When opts.insertGlobals is true, always insert process, global, __filename, and __dirname without analyzing the AST for faster builds but larger output bundles. Default false.

When opts.detectGlobals is true, scan all files for process, global, __filename, and __dirname, defining as necessary. With this option npm modules are more likely to work but bundling takes longer. Default true.

When opts.ignoreMissing is true, ignore require() statements that don't resolve to anything.

When opts.debug is true, add a source map inline to the end of the bundle. This makes debugging easier because you can see all the original files if you are in a modern enough browser.

When opts.standalone is a non-empty string, a standalone module is created with that name and a umd wrapper. You can use namespaces in the standalone global export using a . in the string name as a separator, for example 'A.B.C'. The global export will be sanitized and camel cased.

Note that in standalone mode the require() calls from the original source will still be around, which may trip up AMD loaders scanning for require() calls. You can remove these calls with derequire:

$ npm install derequire
$ browserify main.js --standalone Foo | derequire > bundle.js

opts.insertGlobalVars will be passed to insert-module-globals as the opts.vars parameter.

opts.externalRequireName defaults to 'require' in expose mode but you can use another name.

opts.bare creates a bundle that does not include Node builtins, and does not replace global Node variables except for __dirname and __filename.

opts.node creates a bundle that runs in Node and does not use the browser versions of dependencies. Same as passing { bare: true, browserField: false }.

Note that if files do not contain javascript source code then you also need to specify a corresponding transform for them.

All other options are forwarded along to module-deps and browser-pack directly.

b.add(file, opts)

Add an entry file from file that will be executed when the bundle loads.

If file is an array, each item in file will be added as an entry file.

b.require(file, opts)

Make file available from outside the bundle with require(file).

The file param is anything that can be resolved by require.resolve(), including files from node_modules. Like with require.resolve(), you must prefix file with ./ to require a local file (not in node_modules).

file can also be a stream, but you should also use opts.basedir so that relative requires will be resolvable.

If file is an array, each item in file will be required. In file array form, you can use a string or object for each item. Object items should have a file property and the rest of the parameters will be used for the opts.

Use the expose property of opts to specify a custom dependency name. require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular')

b.bundle(cb)

Bundle the files and their dependencies into a single javascript file.

Return a readable stream with the javascript file contents or optionally specify a cb(err, buf) to get the buffered results.

b.external(file)

Prevent file from being loaded into the current bundle, instead referencing from another bundle.

If file is an array, each item in file will be externalized.

If file is another bundle, that bundle's contents will be read and excluded from the current bundle as the bundle in file gets bundled.

b.ignore(file)

Prevent the module name or file at file from showing up in the output bundle.

If file is an array, each item in file will be ignored.

Instead you will get a file with module.exports = {}.

b.exclude(file)

Prevent the module name or file at file from showing up in the output bundle.

If file is an array, each item in file will be excluded.

If your code tries to require() that file it will throw unless you've provided another mechanism for loading it.

b.transform(tr, opts={})

Transform source code before parsing it for require() calls with the transform function or module name tr.

If tr is a function, it will be called with tr(file) and it should return a through-stream that takes the raw file contents and produces the transformed source.

If tr is a string, it should be a module name or file path of a transform module with a signature of:

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

You don't need to necessarily use the through module. Browserify is compatible with the newer, more verbose Transform streams built into Node v0.10.

Here's how you might compile coffee script on the fly using .transform():

var coffee = require('coffee-script');
var through = require('through');

b.transform(function (file) {
    var data = '';
    return through(write, end);

    function write (buf) { data += buf }
    function end () {
        this.queue(coffee.compile(data));
        this.queue(null);
    }
});

Note that on the command-line with the -c flag you can just do:

$ browserify -c 'coffee -sc' main.coffee > bundle.js

Or better still, use the coffeeify module:

$ npm install coffeeify
$ browserify -t coffeeify main.coffee > bundle.js

If opts.global is true, the transform will operate on ALL files, despite whether they exist up a level in a node_modules/ directory. Use global transforms cautiously and sparingly, since most of the time an ordinary transform will suffice. You can also not configure global transforms in a package.json like you can with ordinary transforms.

Global transforms always run after any ordinary transforms have run.

Transforms may obtain options from the command-line with subarg syntax:

$ browserify -t [ foo --bar=555 ] main.js

or from the api:

b.transform('foo', { bar: 555 })

In both cases, these options are provided as the second argument to the transform function:

module.exports = function (file, opts) { /* opts.bar === 555 */ }

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

b.plugin(plugin, opts)

Register a plugin with opts. Plugins can be a string module name or a function the same as transforms.

plugin(b, opts) is called with the browserify instance b.

For more information, consult the plugins section below.

b.pipeline

There is an internal labeled-stream-splicer pipeline with these labels:

  • 'record' - save inputs to play back later on subsequent bundle() calls
  • 'deps' - module-deps
  • 'json' - adds module.exports= to the beginning of json files
  • 'unbom' - remove byte-order markers
  • 'unshebang' - remove #! labels on the first line
  • 'syntax' - check for syntax errors
  • 'sort' - sort the dependencies for deterministic bundles
  • 'dedupe' - remove duplicate source contents
  • 'label' - apply integer labels to files
  • 'emit-deps' - emit 'dep' event
  • 'debug' - apply source maps
  • 'pack' - browser-pack
  • 'wrap' - apply final wrapping, require= and a newline and semicolon

You can call b.pipeline.get() with a label name to get a handle on a stream pipeline that you can push(), unshift(), or splice() to insert your own transform streams.

b.reset(opts)

Reset the pipeline back to a normal state. This function is called automatically when bundle() is called multiple times.

This function triggers a 'reset' event.

package.json

browserify uses the package.json in its module resolution algorithm, just like node. If there is a "main" field, browserify will start resolving the package at that point. If there is no "main" field, browserify will look for an "index.js" file in the module root directory. Here are some more sophisticated things you can do in the package.json:

browser field

There is a special "browser" field you can set in your package.json on a per-module basis to override file resolution for browser-specific versions of files.

For example, if you want to have a browser-specific module entry point for your "main" field you can just set the "browser" field to a string:

"browser": "./browser.js"

or you can have overrides on a per-file basis:

"browser": {
  "fs": "level-fs",
  "./lib/ops.js": "./browser/opts.js"
}

Note that the browser field only applies to files in the local module, and like transforms, it doesn't apply into node_modules directories.

browserify.transform

You can specify source transforms in the package.json in the browserify.transform field. There is more information about how source transforms work in package.json on the module-deps readme.

For example, if your module requires brfs, you can add

"browserify": { "transform": [ "brfs" ] }

to your package.json. Now when somebody require()s your module, brfs will automatically be applied to the files in your module without explicit intervention by the person using your module. Make sure to add transforms to your package.json dependencies field.

events

b.on('file', function (file, id, parent) {})

b.pipeline.on('file', function (file, id, parent) {})

When a file is resolved for the bundle, the bundle emits a 'file' event with the full file path, the id string passed to require(), and the parent object used by browser-resolve.

You could use the file event to implement a file watcher to regenerate bundles when files change.

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

b.pipeline.on('package', function (pkg) {})

When a package file is read, this event fires with the contents. The package directory is available at pkg.__dirname.

b.on('bundle', function (bundle) {})

When .bundle() is called, this event fires with the bundle output stream.

b.on('reset', function () {})

When the .reset() method is called or implicitly called by another call to .bundle(), this event fires.

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

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

When a transform is applied to a file, the 'transform' event fires on the bundle stream with the transform stream tr and the file that the transform is being applied to.

plugins

For some more advanced use-cases, a transform is not sufficiently extensible. Plugins are modules that take the bundle instance as their first parameter and an option hash as their second.

Plugins can be used to do perform some fancy features that transforms can't do. For example, factor-bundle is a plugin that can factor out common dependencies from multiple entry-points into a common bundle. Use plugins with -p and pass options to plugins with subarg syntax:

browserify x.js y.js -p [ factor-bundle -o bundle/x.js -o bundle/y.js ] \
  > bundle/common.js

For a list of plugins, consult the browserify-plugin tag on npm.

list of source transforms

There is a wiki page that lists the known browserify transforms.

If you write a transform, make sure to add your transform to that wiki page and add a package.json keyword of browserify-transform so that people can browse for all the browserify transforms on npmjs.org.

third-party tools

There is a wiki page that lists the known browserify tools.

If you write a tool, make sure to add it to that wiki page and add a package.json keyword of browserify-tool so that people can browse for all the browserify tools on npmjs.org.

changelog

Releases are documented in changelog.markdown and on the browserify twitter feed.

license

MIT

browserify!

browser-resolve's People

Contributors

airportyh avatar andreypopp avatar defunctzombie avatar f5io avatar forbeslindesay avatar goto-bus-stop avatar hakatashi avatar jameskyburz avatar jaredhanson avatar jmm avatar juliangruber avatar justinbmeyer avatar kriskowal avatar lhorie avatar marionebl avatar matthewp avatar mkillianey avatar msokk avatar mtth avatar mvayngrib avatar roncli avatar rwjblue avatar securingsincity avatar src-code avatar thlorenz avatar timoxley avatar tonistiigi avatar tootallnate avatar trysound avatar wilsonjackson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

browser-resolve's Issues

Using the paths option, doesn't lookup anymore on node_modules

The doc says:

paths - require.paths array to use if nothing is found on the normal node_modules recursive walk

Actually, I have a configuration where the following works:

    return browserify({
            entries: ['./src/js/app.js'],
            extensions: ['.jsx'],
            paths: ['./node_modules','./src/js/home']
        })

While the following doesn't:

    return browserify({
            entries: ['./src/js/app.js'],
            extensions: ['.jsx'],
            paths: ['./src/js/home']
        })

So, I guess when using the paths option, the code doesn't try anymore to lookup into the node modules, while the doc says it should

Use resolve 1.1.6

1.1.6 has an important bug fix browserify/resolve#77 that is not in Browserify currently because browser-resolve is pinned to 1.1.5. Is there a reason why it is pinned this way? If not can this be updated so that the fix makes its way to Browserify? @defunctzombie @substack

Resolve fails for requires without file extension

Ran into an issue recently running module-deps, which depends on browser-resolve, where a package which has a dependency with a browser field defined failed to resolve browser assets because the require() call omits the filename extension.

For example, package asap v2.0.3 defines the following browser field in package.json:

"browser": {
    "./asap.js": "./browser-asap.js",
    "./raw.js": "./browser-raw.js",
    "./test/domain.js": "./test/browser-domain.js"
  },

And in a module such as promise, you'll find a require() such as:

var asap = require('asap/raw')

This fails to resolve because browser-resolve doesn't seem to handle the missing extension when looking up the file in the browser field. Adding the .js extension to the require() call fixes the issue.

Here's a simple test case calling resolve() directly:

var resolve = require('browser-resolve');

resolve('asap/raw', {}, function (err, path) {
    console.log('asap/raw -> ', path);
});

resolve('asap/raw.js', {}, function (err, path) {
    console.log('asap/raw.js -> ', path);
});

Output:

asap/raw.js ->  /Users/steve/git/browser-resolve-bug/node_modules/asap/browser-raw.js
asap/raw ->  /Users/steve/git/browser-resolve-bug/node_modules/asap/raw.js

It'd be great if browser-resolve could resolve the missing extension automatically, otherwise tools like module-deps won't work with packages using shortened filenames.

extract node buildins

hey @shtylman

is there any chance we can extract all replacements for node.js buildin node modules into a separate module (i. e. "node-browser-core"), which exports them the way you filled them into core:

{
  fs: "/path/to/node_modules/node-browser-core/buildin/fs.js",
  http: "/path/to/node_modules/node-browser-core/node_modules/http-browserify/index.js",
  /* ... */
}

This module would be a good place for tests too...

I would like to use it for webpack. I think it's a good idea to have only one place for browser node.js libs, which can be used by every bundler...

@substack @Raynos

alt-browser fallback to "browser" for browserification of dependencies?

this is a question. If A depends on B, and their package.json's look like:

A:

    {
      ...
      "chromeapp": {
        "dgram": "chrome-dgram"
      },
      "dependencies": {
        "B": "^1.0.0"
      }
      ...
    }

B:

    {
      ...
      "browser": {
        "url": "./browser-url.js"
      }
      ...
    }

when you issue:

    browserify --browser chromeapp A/main.js

should browserify fall back to the "browser" field when it browserifies B and needs to resolve "url" but doesn't find a "chromeapp" field? It seems like in most cases this would be desirable. What do you think?

purpose of empty.js

I see some 404 requests with the url /Users/julian/pro/xxx/node_modules/browserify/node_modules/browser-resolve/empty.js, what's that about?

Feature Request: Resolve Modules

In addition to paths, it would be nice to resolve module names:

"browser": "foo"

Before npm used to dedupe packages, it was possible to reliably do something like:

"browser": "./node_modules/foo/index.js"

Happy to open a PR - I just wanted to check if this is desirable or not first.

npm install failing

This might be some sort of issue with npm. I remember there being a similar issue ~1 year ago where valid package.json was returning this same error.

$ npm install browser-resolve
npm ERR! Failed to parse json
npm ERR! Unexpected end of input
npm ERR! File: /Users/morgan/.npm/browser-resolve/1.3.2/package/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR! 
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! System Darwin 13.3.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "browser-resolve"
npm ERR! cwd /Users/morgan/Documents/scratch
npm ERR! node -v v0.10.31
npm ERR! npm -v 1.4.23
npm ERR! file /Users/morgan/.npm/browser-resolve/1.3.2/package/package.json
npm ERR! code EJSONPARSE
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/morgan/Documents/scratch/npm-debug.log
npm ERR! not ok code 0

Resolved files do not respect the `extensions` option

Given a browser field like the following

{
  './value': './value.browser'
}

It looks like this lib properly handles the missing file extension on ./value, but does no handling of the file that it maps to (./value.browser). I think if the extensions property was provided and a browser mapping does not exist on the filesystem, we should iterate through the extensions property to see if any of the resulting paths does exist on the filesystem.

Thoughts?

Reproducer: https://github.com/dcherman/jest-browser-reproducer
Ref: jestjs/jest#6005

support module replacement outside current module

I have a few packages, which form a tree like so.

โ””โ”ฌ application
 โ””โ”ฌ my-module
  โ””โ”ฌ vendor-module
   โ”” foo

For optimizationsโ€”and library sizeโ€”I'd like to replace the foo module. This is ordinarily extremely easy:

{
  "name": "vendor-module",
  "browser": {
    "foo": "foo-replacement"
  }
}

This poses a problem for me: foo would become a functioning browserify module, a shim is not required; making this change and pushing upstream doesn't make much sense (and would likely be rejected).

I would prefer to be able to define module replacements a level up in my-module. However, node-browser-resolve only checks against the first package.json encountered.

Is recursing up packages and checking a viable change? If not, what alternatives do I have?

resolve updates

I just fixed some very tricky issues in resolve that were cropping up in browserify and are now part of the test suite. I recommend upgrading to 1.1.3, since the current tests fail when browser-resolve uses the old version.

The updates address some errors with the previous opts.pathFilter implementation and some very subtle bugs when there is a ./file.js and a ./file directory.

Maintenance

Hi @defunctzombie, this module is heavily used by browserify and we'd like to do some updates (like bumping the resolve dependency). I understand you're not actively working on this package and I'd be happy to maintain it for the foreseeable future. Would you be open to transfering it to the @browserify org? Thanks!

Breakage when a browser shim file does not exist

Near as I can tell, part of the contract of the "resolve" operation is that it will always return a path to an extant file, provided that it does not throw an exception. This module breaks that contract. It does not check anywhere whether the files specified in the "browser" field actually exist, so it can potentially return paths to nonexistent files.

I'm having some trouble expressing the specific problem here, so I'm going to explain it by writing some failing tests in the near future.

Can't resolve 'fs'

Hi,
I have having an issue with this package, as soon as I try to import it I am getting the following error:

Failed to compile.

./node_modules/browser-resolve/index.js
Module not found: Can't resolve 'fs' in 'node_modules/browser-resolve'

Any idea what could cause this issue?

Readme should be more accurate

  1. It seems that options are not limited to the listed 5. "basedir", "extensions" in the resolve package can also be used, but I can't find that in readme.
  2. There are some typo in the examples. For example,
var shims = {
    http: '/your/path/to/http.js'
};

var resolve = require('browser-resolve');
resolve('fs', { modules: shims }, function(err, path) {
    console.log(path);
});

I think it should be resolve('http')?

In the "Browser Field" section, why is there a "chromeapp" property?

events.EventEmitter.removeAllListeners removes no listeners if no arguments are passed

Actuall EventEmitter.prototype.removeAllListeners implementation looks like this:

EventEmitter.prototype.removeAllListeners = function(type) {
  if (arguments.length === 0) {
    this._events = {};
    return this;
  }

  // does not use listeners(), so no side effect of creating _events[type]
  if (type && this._events && this._events[type]) this._events[type] = null;
  return this;
};

It could be found in ./lib/events.js of http://nodejs.org/dist/v0.8.18/node-v0.8.18.tar.gz.

But node-browserify/builtins/events.js has following implementation:

EventEmitter.prototype.removeAllListeners = function(type) {
  // does not use listeners(), so no side effect of creating _events[type]
  if (type && this._events && this._events[type]) this._events[type] = null;
  return this;
};

Such difference results in unexpected behavior of emitter.removeAllListeners() method call in broserified version of Node app.
Expected: All listeners of all types are removed.
Actual: No listeners removed.

Button on IE not working - works on all other browser

I am hoping this is the proper place to submit this.

I am exporting a PDF using PDF kit, to which I have added node_modules/browser-resolve.

When I click the PDF button in any browser, it properly launches or downloads the PDF, except for MS Edge or any other IE version.

Any thoughts on how I can resolve this?

"resolve.mainFields"-like support

Was deep in the bowels of a large webpack.config.js file and came across a challenge that this package seems perfect for solving โ€“ย with one kinda catch.

That is: nearly all of the time I want to resolve against "module", which I can believe is possible this way after reading the docs:

resolve.sync('@scope/my-module', { browser: 'module' });

However, in the absence of "module" I would like to fall-back to "browser". This is handled in webpack land as resolve.mainFields.

Is there interest in this feature? Does it already exist and I overlooked it in the code?

p.s. long-time no speak. Hope you are well.

wrong comment line

File node-browser-resolve/test/fixtures-coffee/foo.coffee consist of a string // blank file. Isn't it correct to change it to # blank file. It throws errors as it is.

`constants` builtin is missing

found by trying to browserify the following:

var request = require('request')
  , parse = require('tar').Parse

var pre = document.createElement('pre')

request
  .get('/example.tar')
  .pipe(parse())
  .on('entry', function(e) {
    pre.textContent += e.props.path + '\n'
  })

i think it should just be:

module.exports = {"O_RDONLY":0,"O_WRONLY":1,"O_RDWR":2,"S_IFMT":61440,"S_IFREG":32768,"S_IFDIR":16384,"S_IFCHR":8192,"S_IFBLK":24576,"S_IFIFO":4096,"S_IFLNK":40960,"S_IFSOCK":49152,"O_CREAT":512,"O_EXCL":2048,"O_NOCTTY":131072,"O_TRUNC":1024,"O_APPEND":8,"O_DIRECTORY":1048576,"O_NOFOLLOW":256,"O_SYNC":128,"O_SYMLINK":2097152,"S_IRWXU":448,"S_IRUSR":256,"S_IWUSR":128,"S_IXUSR":64,"S_IRWXG":56,"S_IRGRP":32,"S_IWGRP":16,"S_IXGRP":8,"S_IRWXO":7,"S_IROTH":4,"S_IWOTH":2,"S_IXOTH":1,"E2BIG":7,"EACCES":13,"EADDRINUSE":48,"EADDRNOTAVAIL":49,"EAFNOSUPPORT":47,"EAGAIN":35,"EALREADY":37,"EBADF":9,"EBADMSG":94,"EBUSY":16,"ECANCELED":89,"ECHILD":10,"ECONNABORTED":53,"ECONNREFUSED":61,"ECONNRESET":54,"EDEADLK":11,"EDESTADDRREQ":39,"EDOM":33,"EDQUOT":69,"EEXIST":17,"EFAULT":14,"EFBIG":27,"EHOSTUNREACH":65,"EIDRM":90,"EILSEQ":92,"EINPROGRESS":36,"EINTR":4,"EINVAL":22,"EIO":5,"EISCONN":56,"EISDIR":21,"ELOOP":62,"EMFILE":24,"EMLINK":31,"EMSGSIZE":40,"EMULTIHOP":95,"ENAMETOOLONG":63,"ENETDOWN":50,"ENETRESET":52,"ENETUNREACH":51,"ENFILE":23,"ENOBUFS":55,"ENODATA":96,"ENODEV":19,"ENOENT":2,"ENOEXEC":8,"ENOLCK":77,"ENOLINK":97,"ENOMEM":12,"ENOMSG":91,"ENOPROTOOPT":42,"ENOSPC":28,"ENOSR":98,"ENOSTR":99,"ENOSYS":78,"ENOTCONN":57,"ENOTDIR":20,"ENOTEMPTY":66,"ENOTSOCK":38,"ENOTSUP":45,"ENOTTY":25,"ENXIO":6,"EOPNOTSUPP":102,"EOVERFLOW":84,"EPERM":1,"EPIPE":32,"EPROTO":100,"EPROTONOSUPPORT":43,"EPROTOTYPE":41,"ERANGE":34,"EROFS":30,"ESPIPE":29,"ESRCH":3,"ESTALE":70,"ETIME":101,"ETIMEDOUT":60,"ETXTBSY":26,"EWOULDBLOCK":35,"EXDEV":18,"SIGHUP":1,"SIGINT":2,"SIGQUIT":3,"SIGILL":4,"SIGTRAP":5,"SIGABRT":6,"SIGIOT":6,"SIGBUS":10,"SIGFPE":8,"SIGKILL":9,"SIGUSR1":30,"SIGSEGV":11,"SIGUSR2":31,"SIGPIPE":13,"SIGALRM":14,"SIGTERM":15,"SIGCHLD":20,"SIGCONT":19,"SIGSTOP":17,"SIGTSTP":18,"SIGTTIN":21,"SIGTTOU":22,"SIGURG":16,"SIGXCPU":24,"SIGXFSZ":25,"SIGVTALRM":26,"SIGPROF":27,"SIGWINCH":28,"SIGIO":23,"SIGSYS":12,"SSL_OP_ALL":-2147479553,"SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION":262144,"SSL_OP_CIPHER_SERVER_PREFERENCE":4194304,"SSL_OP_CISCO_ANYCONNECT":32768,"SSL_OP_COOKIE_EXCHANGE":8192,"SSL_OP_CRYPTOPRO_TLSEXT_BUG":-2147483648,"SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS":2048,"SSL_OP_EPHEMERAL_RSA":2097152,"SSL_OP_LEGACY_SERVER_CONNECT":4,"SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER":32,"SSL_OP_MICROSOFT_SESS_ID_BUG":1,"SSL_OP_MSIE_SSLV2_RSA_PADDING":64,"SSL_OP_NETSCAPE_CA_DN_BUG":536870912,"SSL_OP_NETSCAPE_CHALLENGE_BUG":2,"SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG":1073741824,"SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG":8,"SSL_OP_NO_COMPRESSION":131072,"SSL_OP_NO_QUERY_MTU":4096,"SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION":65536,"SSL_OP_NO_SSLv2":16777216,"SSL_OP_NO_SSLv3":33554432,"SSL_OP_NO_TICKET":16384,"SSL_OP_NO_TLSv1":67108864,"SSL_OP_PKCS1_CHECK_1":134217728,"SSL_OP_PKCS1_CHECK_2":268435456,"SSL_OP_SINGLE_DH_USE":1048576,"SSL_OP_SINGLE_ECDH_USE":524288,"SSL_OP_SSLEAY_080_CLIENT_DH_BUG":128,"SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG":16,"SSL_OP_TLS_BLOCK_PADDING_BUG":512,"SSL_OP_TLS_D5_BUG":256,"SSL_OP_TLS_ROLLBACK_BUG":8388608,"NPN_ENABLED":1}

require('utils') + JSON.parse

Should built_ins/utils and friends use jsonify instead of JSON.parse and JSON.stringify

This allows us to use require('utils') in IE<8

resolving with pkg metadata breaks browserify

Here is the command I'm running from level-dump to get the following error:

~/dev/js/projects/level-dump (master %)
โž  browserify test/*.js > bundle.js

/usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:91
                        var dir = path.resolve(x, pkg.main);
                                                     ^
TypeError: Cannot read property 'main' of undefined
    at module.exports.dir (/usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:91:54)
    at load (/usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:54:43)
    at module.exports.cb (/usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:60:22)
    at module.exports.isFile (/usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:16:47)
    at Object.oncomplete (fs.js:297:15)

To reproduce just clone that repo and repeat the above step.

Update resolve dependency to 1.12.0

The following tests fail with resolve 1.12.0

$ mocha -R spec


  โœ“ shim found
  โœ“ core shim not found
  โœ“ shim found
  โœ“ core shim not found
  โœ“ module to implicit extension
  โœ“ implicit extension to implicit extension
  โœ“ implicit extension to implicit extension
  โœ“ explicit extension to explicit extension
  โœ“ implicit extension to explicit extension
  โœ“ module implicit extension to explicit extension
  โœ“ module implicit extension to explicit extension
  โœ“ false file
  โœ“ false module
  โœ“ false file
  โœ“ false module
  โœ“ false expand path
  โœ“ local
  โœ“ local
  โœ“ local
  โœ“ index.js of module dir
  โœ“ alternate main
  โœ“ string browser field as main
  โœ“ string browser field as main - require subfile
  โœ“ object browser field as main
  โœ“ object browser field replace file
  โœ“ object browser field replace file - no paths
  โœ“ replace module in browser field object
  โœ“ index.js of module dir
  โœ“ alternate main
  โœ“ string browser field as main
  โœ“ string browser field as main - require subfile
  โœ“ object browser field as main
  โœ“ object browser field as main
  โœ“ object browser field replace file
  โœ“ test foobar -> module-b replacement
  โœ“ test ./x -> ./y replacement
  โœ“ test core -> module-c replacement
  โœ“ test foobar -> module-b replacement with transform
  โœ“ test foobar -> module-i replacement with transform in replacement
  โœ“ object browser field replace file - no paths
  โœ“ replace module in browser field object
  โœ“ override engine shim
  โœ“ alt-browser field
  1) index.js of module dir
  โœ“ alternate main
  โœ“ string browser field as main
  โœ“ string browser field as main - require subfile
  โœ“ string alt browser field as main - require subfile
  โœ“ object browser field as main
  โœ“ object browser field as main
  2) deep module reference mapping
  3) deep module reference mapping without file extension - .js
  4) deep module reference mapping without file extension - .json
  โœ“ object browser field replace file
  โœ“ test foobar -> module-b replacement
  โœ“ test core -> module-c replacement
  โœ“ test core -> module-c replacement with alt browser
  โœ“ test foobar -> module-b replacement with transform
  โœ“ test ./x -> ./y replacement
  โœ“ test foobar -> module-i replacement with transform in replacement
  โœ“ object browser field replace file - no paths
  โœ“ replace module in browser field object
  โœ“ override engine shim
  โœ“ alt-browser field
  5) alt-browser deep module reference mapping
  โœ“ alt-browser fallback to "browser" on deps of deps
  6) not fail on accessing path name defined in Object.prototype

  61 passing (198ms)
  6 failing

  1) index.js of module dir:
     Uncaught AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B:
+ expected - actual

- {
-   main: 'fixtures'
- }
+ undefined
      at test/modules.js:11:16
      at index.js:269:13
      at node_modules/resolve/lib/async.js:93:25
      at maybeUnwrapSymlink (node_modules/resolve/lib/async.js:35:9)
      at node_modules/resolve/lib/async.js:89:24
      at ondir (node_modules/resolve/lib/async.js:264:27)
      at onex (node_modules/resolve/lib/async.js:161:32)
      at node_modules/resolve/lib/async.js:11:20
      at FSReqWrap.oncomplete (fs.js:155:5)

  2) deep module reference mapping:
     Uncaught AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Cannot find module 'module-l/direct' from '/home/vagrant/forge/debian/git/js-team/node-browser-resolve/test/fixtures'
      at test/modules.js:95:16
      at index.js:265:24
      at node_modules/resolve/lib/async.js:99:17
      at node_modules/resolve/lib/async.js:97:35
      at processDirs (node_modules/resolve/lib/async.js:244:39)
      at isdir (node_modules/resolve/lib/async.js:251:32)
      at node_modules/resolve/lib/async.js:23:69
      at FSReqWrap.oncomplete (fs.js:154:21)

  3) deep module reference mapping without file extension - .js:
     Uncaught AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Cannot find module 'module-n/foo' from '/home/vagrant/forge/debian/git/js-team/node-browser-resolve/test/fixtures'
      at test/modules.js:106:16
      at index.js:265:24
      at node_modules/resolve/lib/async.js:99:17
      at node_modules/resolve/lib/async.js:97:35
      at processDirs (node_modules/resolve/lib/async.js:244:39)
      at isdir (node_modules/resolve/lib/async.js:251:32)
      at node_modules/resolve/lib/async.js:23:69
      at FSReqWrap.oncomplete (fs.js:154:21)

  4) deep module reference mapping without file extension - .json:
     Uncaught AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Cannot find module 'module-n/bar' from '/home/vagrant/forge/debian/git/js-team/node-browser-resolve/test/fixtures'
      at test/modules.js:113:16
      at index.js:265:24
      at node_modules/resolve/lib/async.js:99:17
      at node_modules/resolve/lib/async.js:97:35
      at processDirs (node_modules/resolve/lib/async.js:244:39)
      at isdir (node_modules/resolve/lib/async.js:251:32)
      at node_modules/resolve/lib/async.js:23:69
      at FSReqWrap.oncomplete (fs.js:154:21)

  5) alt-browser deep module reference mapping:

      Uncaught AssertionError [ERR_ASSERTION]: '/home/vagrant/forge/debian/git/js-team/node-browser-resolve/test/fixtures/node_modules/alt-browser-field/direct.js' == '/home/vagrant/forge/debian/git/js-team/node-browser-resolve/test/fixtures/node_modules/alt-browser-field/chromeapp-direct.js'
      + expected - actual

      -/home/vagrant/forge/debian/git/js-team/node-browser-resolve/test/fixtures/node_modules/alt-browser-field/direct.js
      +/home/vagrant/forge/debian/git/js-team/node-browser-resolve/test/fixtures/node_modules/alt-browser-field/chromeapp-direct.js
      
      at test/modules.js:292:16
      at index.js:269:13
      at node_modules/resolve/lib/async.js:93:25
      at maybeUnwrapSymlink (node_modules/resolve/lib/async.js:35:9)
      at node_modules/resolve/lib/async.js:89:24
      at onfile (node_modules/resolve/lib/async.js:258:27)
      at onex (node_modules/resolve/lib/async.js:161:32)
      at node_modules/resolve/lib/async.js:11:20
      at FSReqWrap.oncomplete (fs.js:155:5)

  6) not fail on accessing path name defined in Object.prototype:

      Uncaught AssertionError [ERR_ASSERTION]: 'toString' == '/home/vagrant/forge/debian/git/js-team/node-browser-resolve/test/fixtures/node_modules/toString/index.js'
      + expected - actual

      -toString
      +/home/vagrant/forge/debian/git/js-team/node-browser-resolve/test/fixtures/node_modules/toString/index.js
      
      at test/modules.js:317:16
      at index.js:269:13
      at node_modules/resolve/lib/async.js:87:38
      at ondir (node_modules/resolve/lib/async.js:264:27)
      at onex (node_modules/resolve/lib/async.js:161:32)
      at node_modules/resolve/lib/async.js:11:20
      at FSReqWrap.oncomplete (fs.js:155:5)

dgram shim

While trying to browserify request I noticed that we don't have a dummy shim for the 'dgram' module:

$ browserify main.js > bundle.js

stream.js:81
      throw er; // Unhandled stream error in pipe.
            ^
Error: module not found: "dgram" from file /home/substack/projects/request-browser-test/node_modules/request/node_modules/hawk/node_modules/sntp/lib/index.js
    at /home/substack/projects/node-browserify/node_modules/module-deps/index.js:55:52
    at Browserify._resolve (/home/substack/projects/node-browserify/index.js:286:9)
    at resolve (/home/substack/projects/node-browserify/node_modules/browser-resolve/index.js:49:16)
    at Browserify._resolve (/home/substack/projects/node-browserify/index.js:281:12)
    at walk (/home/substack/projects/node-browserify/node_modules/module-deps/index.js:53:9)
    at module.exports.rec.id (/home/substack/projects/node-browserify/node_modules/module-deps/index.js:107:13)
    at Array.forEach (native)
    at parseDeps (/home/substack/projects/node-browserify/node_modules/module-deps/index.js:106:14)
    at done (/home/substack/projects/node-browserify/node_modules/module-deps/index.js:96:13)
    at applyTransforms (/home/substack/projects/node-browserify/node_modules/module-deps/index.js:79:41)

Just an empty file would do.

options passed to resolve

I ran into an issue with browserify, which uses browser-resolve, in that it wasn't finding .coffee files. It turns out this was because it (unlike node loaded with require('coffee-script')) requires the full extension -- require('foo.coffee') instead of require('foo'), which is definitely not something you want to do (it locks you into coffee files, won't use the .js if you "transpile" it, etc.)

Browser-resolve uses resolve and resolve has an option to add file extensions using the extensions key in its command options, but resolve's options aren't exposed in the browser-resolve API, so there's no way to add this file extension when using browser-resolve and thus no way to do it in browserify.

I think browser-resolve should pass the options it receives onto the internal resolve call by copying the keys over from parent.

Synchronous version?

It would be nice if a synchronous counterpart were provided. As far as I can tell, that would only require swapping out the calls to fs.readFile and resolve for their synchronous versions. I can submit a PR if interested.

Feature request: option to intercept all disk I/O

I want browser-resolve to always go through my provided functions rather than touching the disk directly. This is because I have an in-memory asset pipeline and I want to be able to expose files to browser-resolve that it wouldn't be able to find on disk (because they don't actually exist on disk, they exist only in my in-memory cache, having being transformed from other filetypes on disk).

Would it be possible to accept an optional callback, readFile (for example) which, if provided, would be used by browser-resolve instead of fs.readFile? And also maybe a custom isFile option, or whatever else it needs? Obviously these functions would be required to implement a standard node async signature.

I need to be able to intercept and carry out all disk accesses that browser-resolve does when resolving something, including all stat calls and file reads, for all package.jsons etc.

support recursivity in paths option

See http://stackoverflow.com/a/23608416/82609

Imagine I have the following directory structure

/js/module1.js
/js/module2.js
/js/dir1/module3.js
/js/dir2/module4.js

I want to be able to do:
require("module1"); require("module2"); require("module3"); require("module4");

With browserify, I have to use:

browserify(
  './app', 
  {
    paths: [
      './js',
      './js/dir1',
      './js/dir2',
    ]
  }
);

This is annoying because I have to maintain a list of all js directories inside my build

Is there anything we could do?

The other solution would be to use:

require("module1"); require("module2"); require("dir1/module3"); require("dir2/module4");

which is not so bad anyway

Make browser field adjust incoming "deep" module references.

Related to browserify/browserify#1065 (comment)

I'd like a browser field like:

browser: {
  "./control": "./dist/cjs/control"
}

To be able to adjust a mapping like:

require("can/control") //-> to can/dist/cjs/control

To make this work, one might only have to make paths include the dependency module's path (node_modules/can) if the id is not relative around here: https://github.com/defunctzombie/node-browser-resolve/blob/master/index.js#L200

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.