Giter Club home page Giter Club logo

browserify-handbook'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!

browserify-handbook's People

Contributors

adam-lynch avatar ahutchings avatar blixt avatar bttmly avatar cuth avatar daniel-hug avatar denysdovhan avatar genki-s avatar gmaclennan avatar goto-bus-stop avatar guiltydolphin avatar hkdobrev avatar jimrhoskins avatar kidkarolis avatar lukekarrys avatar macil avatar madbence avatar marlun78 avatar mathiasbynens avatar mattdesl avatar nornagon avatar olizilla avatar seanewest avatar stevemao avatar tkurki avatar treythomas123 avatar trott avatar ungoldman avatar yousefcisco avatar yursha 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  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

browserify-handbook's Issues

UI elements in npm?

I really like the section about creating a small reusable widget in HTML. I wonder if people do that in practice and if one can find such packages in npm? @substack what's your experience? Do you write everything yourself everytime?

External bundles

As explain here: https://github.com/substack/browserify-handbook#external-bundles
I do the following:

npm install jquery
browserify -r jquery --standalone jquery > jquery-bundle.js
browserify main.js --exclude jquery > bundle.js

index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>My Site</title>
  <script src="jquery-bundle.js"></script>
  <script src="bundle.js"></script>
</head>
<body>
    <h1>My Site</h1>
</body>
</html>

main.js:

var $ = require('jquery');
$(window).click(function () { document.body.bgColor = 'red' });

And when I open my page I get Uncaught Error: Cannot find module 'jquery'

Is it a code bug, a doc bug or am I just missing something ?

Standalone applicable?

Hello everyone,

I'm using browserify for bundling my HttpClient with Bluebird for promises, since it has to be cross-browser compatible and IE does not support promises natively.
Now I'm having the issue, that I get the promises returned alright in IE, but since bluebird is only available in my IIFE, I can't use things like Promise.all without having to include bluebird on the page also.
I thought of using standalone for making bluebird available in outer scope. Did I understand correctly, that this is its purpose?
I changed my npm build script to
browserify src/js/WebApiClient.js --standalone XrmWebApiClient > Publish/WebApiClient.js
for making the standalone bundle, however I don't really get the purpose of the XrmWebApiClient object. What is its purpose?

Thanks for your help.

Kind Regards,
Florian

Parsing error when json attribute is named "required"

Browserify throws an error ("Unexpected token :") when importing a JSON file containing a JSON property named "required". Unfortunately, in JSON schema the property "required" is an official keyword.

Example:

File "foo.json" contains the following JSON code:

{
"required": []
}

File "bar.js" requires foo.json:

var foo = require('./foo.json');

In this situation, Browserify fails to parse bar.js with the error message "Unexpected token :".

TypeError: punycode.toASCII is not a function /dist/bundle.js:30114

Hi Guys,

I am new to browserify, and in trying to implement in my local project, I am getting this error after I run my build script in my browser output. I tested my install with a simple button click alert and that worked fine, but when I tried to implement a twitter api (which works perfectly in PhpStorm console), that's when the error started appearing. There's nothing on SO on this issue, and all I could find were problems with AWS, having nothing to do with Browserify.

Here's my main.js file:

main.txt

I am running this locally inside the Symphony3 framework.

testling

Testling CI has been down for super long so what alternative do you suggest?

Thanks.

Add a table of content

Thank you for this useful repo !
However, as the content grow larger, it could prove useful to add a table of content, allowing to quickly jump to a specific section.

Test if is browsified

Hello everybody,

is there a nice / easy way to test if the code ist browsified?

I am using browsify on the backend and I'll try finding out a way if the location of my config files is different than at development time.

Of yourse I can use enviorment variables - and maybe - we have this included in browsify.

Thx!

Builtins section

In the section:

So even if a module does a lot of buffer and stream operations, it will probably just work in the browser, so long as it doesn't do any server IO.

Can you please elaborate or provide an example?

Thanks!

ability to specify alt browser mapping, for chromeapp or firefox app, etc.

when I browserify for a Chrome app, I want a slightly different mapping than I specify in the "browser" field. It would be cool if I could have an arbitrarily named field and tell browserify to use that instead of "browser", e.g.

browserify --browser=chromeapp main.js > bundle.js

and

"browser": {
  ...
},
"chromeapp": {
  ...
}

it would then default to "browser"

globals, but not on window?

Hi,

I am using Browserify in a legacy browser environment, which means that the window namespace is volatile and unsuitable for storing global variables that I want as globals in my bundles (yes, I want that).

So, I need a way to make globals within a build, either per bundle, or for all bundles.

have been googling this for a while, and can't find a suitable solution, any suggestions before I dig into trying to write a plugin that sets stuff on all modules (doable?).

Thanks.

Something short and sweet to help repo owners who are publishing to bower but not npm

We frequently find code we want to use which the authors have happily published to bower, but they haven't published to npm.

You want to help them. You want to encourage them. You want them to understand why browserify is such a great solution and how little work it is to publish to npm.

But you are busy and just move along.

Let's create something short and easy to follow that we can use to help these developers understand and support Browserify.

  • What should it say?
  • Pictures or diagrams?
  • Helpful links?

Demystify exclude

I'm trying to create two bundles. One with React and one that requires React. From the example in the handbook, it looks like exclude might provide what I need.

If I take the jQuery example and adapt it to use React instead of jQuery, I end up with something like this:

$ npm install react
$ browserify -r react --standalone React > react-bundle.js

then we want to just require('react') in a main.js:

console.log(require('react'));

defering to the React dist bundle so that we can write index.html:

<script src="react-bundle.js"></script>
<script src="bundle.js"></script>

and not have the React definition show up in bundle.js, then while compiling the main.js, you can --exclude react:

browserify main.js --exclude react > bundle.js

The problem with this is that when you load index.html you get an uncaught

Error: Cannot find module 'react'

Reading back through the excluding doc, I see that it suggests I might actually expect this behavior:

Another related thing we might want is to completely remove a module from the output so that require('modulename') will fail at runtime.

This completely mystified me the first time I read it. Why would someone want a require() call to fail at runtime??

The other mysterious part to me is why things work with the jQuery example but not React. In the main.js bundle from the jQuery example, the require('jquery') call is replaced with this:

(typeof window !== "undefined" ? window['jQuery'] : typeof global !== "undefined" ? global['jQuery'] : null)

I'm curious how Browserify figured out that jQuery might be assigned to the global. Is this something specific to --exclude jquery?

I'd be happy to help improve the documentation if someone could help me understand exclude.

Getting error `require is not defined` after browserify command

Getting error require is not defined

Uncaught ReferenceError: require is not defined
    at index.html:10:27
(anonymous) @ index.html:10

The command I am using is browserify index.js > browser.js

index.html

<html>
<head>
  <script src="../browser.min.js"></script>
</head>
<body>
  <div id="isbrowser"></div>
  <script>
    const { isBrowser } = require("../index.js");
    console.log(isBrowser());
  </script>
</body>
</html>

browser.min.js

!function n(o,i,u){function c(e,t){if(!i[e]){if(!o[e]){var r="function"==typeof require&&require;if(!t&&r)return r(e,!0);if(f)return f(e,!0);throw(t=new Error("Cannot find module '"+e+"'")).code="MODULE_NOT_FOUND",t}r=i[e]={exports:{}},o[e][0].call(r.exports,function(t){return c(o[e][1][t]||t)},r,r.exports,n,o,i,u)}return i[e].exports}for(var f="function"==typeof require&&require,t=0;t<u.length;t++)c(u[t]);return c}({1:[function(require,e,exports){!function(t){!function(){"use strict";e.exports.isBrowser=function(){return("object"!=typeof t||"function"!=typeof require)&&"function"!=typeof importScripts&&("object"==typeof window||void 0)}}.call(this)}.call(this,require("_process"))},{_process:2}],2:[function(require,t,exports){var r,n,t=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}try{r="function"==typeof setTimeout?setTimeout:o}catch(t){r=o}try{n="function"==typeof clearTimeout?clearTimeout:i}catch(t){n=i}function u(e){if(r===setTimeout)return setTimeout(e,0);if((r===o||!r)&&setTimeout)return(r=setTimeout)(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}var c,f=[],s=!1,l=-1;function a(){s&&c&&(s=!1,c.length?f=c.concat(f):l=-1,f.length)&&h()}function h(){if(!s){for(var t=u(a),e=(s=!0,f.length);e;){for(c=f,f=[];++l<e;)c&&c[l].run();l=-1,e=f.length}c=null,s=!1,!function(e){if(n===clearTimeout)return clearTimeout(e);if((n===i||!n)&&clearTimeout)return(n=clearTimeout)(e);try{n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}(t)}}function p(t,e){this.fun=t,this.array=e}function e(){}t.nextTick=function(t){var e=new Array(arguments.length-1);if(1<arguments.length)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];f.push(new p(t,e)),1!==f.length||s||u(h)},p.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={},t.on=e,t.addListener=e,t.once=e,t.off=e,t.removeListener=e,t.removeAllListeners=e,t.emit=e,t.prependListener=e,t.prependOnceListener=e,t.listeners=function(t){return[]},t.binding=function(t){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(t){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}},{}]},{},[1]);

Document how to load a polyfill in Browserify

Hi,

I have not found any good reference explaining how to load a polyfill into a Browserify app.

I think polyfills must be loaded before other libs as some libs require the polyfill to be present when initialized to work correctly.

This is the case for exemple for FormatJS.io which may require Intl polyfill.

I think the way to go is to use bundle.add("polyfill") as we want to load the polyfill without having to require it, but in case multiple bundle.add are present, can we assume that the entry points will be loaded in order so that we are sure the polyfills are all loaded even before our app entry point is loaded?

This would be nice to document it, as many people may want to load polyfills into browserify apps.

I've explained how I solved my problem on SO: http://stackoverflow.com/questions/27870974/what-is-the-correct-way-to-load-polyfills-and-shims-with-browserify/28964831
But would also like to know if it's a good way to deal with polyfills.

What does it mean?

What does this paragraph means?

node also has a mechanism for searching an array of paths, but this mechanism is deprecated and you should be using node_modules/ unless you have a very good reason not to.

How those two things are releated?

Uncaught TypeError: Invalid Version: at new SemVer

I'm trying out browserify so I created a little node js code with a require('github-db').default in it then run this command.

browserify main.js -o bundle.js

but in the browser, I got "Uncaught TypeError: Invalid Version: at new SemVer" but I don't really know how to proceed. The program works in node. Please help.

package.json

{
  "name": "derelict",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "dependencies": {
    "github-db": "^1.1.3"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Loading bundle aynchronously

It's stated here https://github.com/substack/browserify-handbook#partitioning that:
"You could also load the bundles asynchronously with ajax or by inserting a script tag into the page dynamically"

I wonder how? If I load another bundle dynamically how can I require a file bundled in it? If I try to require it, I'll get Uncaught Error: Cannot find module 'x' because the require function doesn't know about files bundled in it.

don't understand how to convert to browser

Section "bundling for the browser" explains how to convert for browser inclusion.
I'm trying to run virtual-dom directly in browser, so I browserify it:

browserify h.js > bundle.js

h.js contains:

var h = require("./virtual-hyperscript/index.js")
module.exports = h

the generated bundle.js begins with:

(function e(t,n,r){function s(o,u){ ...
var h = require("./virtual-hyperscript/index.js")
module.exports = h

my index.html:

<html>
  <body>
    <script src="bundle.js"></script>
   <script>
   h('div', { ...  // generates ReferenceError: h is not defined
  </body>
</html>

how do I grab the h variable??

Document (or change) nested arrays for package.json transform field?

From babel/babelify#142, it seems the syntax where individual transforms are specified as arrays is correct.

"browserify": {
    "transform": [
        "brfs",
        [
            "babelify", 
            { 
                "presets": ["es2015"] 
            }
        ]
    ]
}

The syntax for this part:

 [
    "babelify", 
    { 
        "presets": ["es2015"] 
    }
 ]

is odd: the array doesn't seem to be used as an ordered list of items. "babelify" is item 0, {"presets": ["es2015"]} is item 1. What would item 2 be?

If there wouldn't ever be an item 2, and this is simply a map between babelify and babelify's options, wouldn't an object be more logical?

"browserify": {
    "transform": [
        "brfs",
        {
            "babelify": { 
                "presets": ["es2015"] 
            }
        }
    ]
} 

How to deal with large browserified bundles?

Where do you begin when you want to analyse and fix bundles that are too large? What steps would you carry out to see what is taking up the most room in a broswerified bundle?

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.