• Stars
    star
    381
  • Rank 112,502 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated almost 3 years ago

Reviews

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

Repository Details

express middleware for browserify, done right

browserify-middleware

middleware for browserify v2 with sensible defaults for the ultimate in ease of use

In addition to the basics, browserify-middleware has the following features out of the box:

  • source-maps are automatically enabled for debugging
  • automatically rebuilds whenever files change in development
  • minification automatically enabled for production
  • gzip automatically enabled for production
  • etags for caching automatically enabled for production

With the exception of serving up directories (which requires req.path from express) everything is entirely framework independent. Simply pass in req res, and a callback that will only be called in the event of an error.

If you think I've missed something, be sure to open an issue or submit a pull request.

Build Status Coverage Status Dependency Status NPM version

Sponsor

Usage

See example directory for a complete server

var browserify = require('browserify-middleware');
var express = require('express');
var app = express();

//provide browserified versions of all the files in a directory
app.use('/js', browserify(__dirname + '/client/dir'));

//provide a browserified file at a path
app.get('/js/file.js', browserify(__dirname + '/client/file.js'));

//provide a bundle exposing `require` for a few npm packages.
app.get('/js/bundle.js', browserify(['hyperquest', 'concat-stream']));

//provide a bundle for a few npm packages plus run main.js
app.get('/js/bundle.js', browserify(['hyperquest', 'concat-stream', {__dirname + '/client/main.js': {run: true}}]));

app.listen(3000);

Multiple Bundles Example

Multiple bundles can sometimes lead to better caching performance. If you had multiple different JavaScript modules in ./client that all depended on hyperquest and concat-stream and were used on different pages, you may want to split those two modules into separate files so that they are only loaded once for someone browsing arround the site:

var shared = ['hyperquest', 'concat-stream'];
app.get('/js/bundle.js', browserify(shared));
app.use('/js', browserify('./client', {external: shared}))

Then on your HTML pages you can just have:

page1.html

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

page2.html

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

This way, booth beep.js and boop.js can require the shared modules (hyperquest and concat-stream) but they aren't actually contained within that file.

API

browserify('./path/to/file.js'[, options])

Return the middleware to serve a browserified version of the file. The file path is relative to the calling module, not to process.cwd().

browserify('./path/to/directory/'[, options])

Return the middleware to serve a browserified version of all the files in a directory. The directory path is relative to the calling module, not to process.cwd().

browserify(['module-a', 'module-b'][, options])

Return middleware that will expose require for each of the modules in the array. This will work even if those modules are also in the external array.

browserify([{'module-d': {expose: 'dee'}}][, options])

Require module-d with custom options (to be passed on to browserify). In this case module-d will be exposed as dee. This can be mixed and matched with plain strings. Note that these modules must not appear in the external array.

options / settings

The options passed to each middleware function override the defaults specified in settings.

Setings has two properties settings.production and settings.development which specify the default settings for each environment. The current environment is specified by settings.mode and defaults to process.env.NODE_ENV || 'development'

Production defaults:

production.cache = true; // equivalent to "public, max-age=60"
production.precompile = true;
production.minify = true;
production.gzip = true;
production.debug = false;

To update:

browserify.settings.production('cache', '7 days');

Development defaults:

development.cache = 'dynamic';
development.precompile = false;
development.minify = false;
development.gzip = false;
development.debug = true;

To update:

browserify.settings.development('gzip', true);

The following defaults are the same for production and development:

external = [];
ignore = [];
ignoreMissing = false;
transform = [];
insertGlobals = false;
detectGlobals = true;
standalone = false;
grep = /\.js$/

To update:

browserify.settings('external', ['hyperquest']);
//or
browserify.settings({
  ignoreMissing: true,
  insertGlobals: true,
  transform: ['rfileify']
});

Custom Environments:

You can also create a new custom environment:

var test = browserify.settings.env('test');
test('minify', true);
//or
test({
  debug: true
});

cache

The cache setting determines how long content can be cached in the client's web browsers (and any caching proxies) and whether or not to cache bundles server side. Any value other than false will result in them being cached server side. The 'dynamic' cache option is special. It works like watchify and only re-compiles the files that have changed. This is the fastest option for development. It does not enable any client side caching.

If cache is true the client will recieve Cache Control of "public, max-age=60", which caches for 60 seconds.

If cache is a string in the form accepted by ms it becomes: "public, max-age=" + (ms(cache)/1000)

If cache is a number, it is treated as being in milliseconds so becomes: "public, max-age=" + (cache/1000)

If cache is an object of the form {private: true || false, maxAge: '10 minutes'} it becomes the apropriate string.

If cache is any other string it will be sent directly to the client.

N.B. that if caching is enabled, the server never times out its cache, no matter what the timeout set for the client.

precompile

The precompile setting enables bundles to be precompiled/built and readily cached immediately on server startup. This option is not available when using browserify with a directory. If precompile is set to true, the bundle will be compiled & cached at server start.

// Precompile a browserified file at a path
app.get('/js/file.js', browserify('./client/file.js', {
  cache: true,
  precompile: true
}));

// Precompile a bundle exposing `require` for a few npm packages.
app.get('/js/bundle.js', browserify(['hyperquest', 'concat-stream'], {
  cache: true,
  precompile: true
}));

N.B. It only makes sense to use precompiling when caching is enabled. If caching is disabled, no precompiling will happen.

minify

If minify is true, UglifyJS will be used to minify the resulting code. This is true by default in production. If you set it to an object, the object will be passed to uglify-js as options:

  • warnings (default false) - pass true to display compressor warnings
  • mangle (default true) - pass false to skip mangling names
  • output (default null) - pass an object to specify additional output options. The defaults are optimized for best compression.
  • compress (default {}) - pass false to skip compressing entirely. Pass an object to specify custom compressor options.

gzip

If gzip is true, GZip will be enabled when clients support it. This increases the memory required for caching by aproximately 50% but the speed boost can be considerable. It is true by default in production.

debug

If debug is true, a source map will be added to the code. This is very useful when debugging. debug is false in production.

basedir

If debug is true you can provide a string pathname for basedir and the paths of your files in the source-map will be displayed relative to that file. This is great for hiding the details of your local file system or tidying up the debugging of a large app.

plugins

An array of objects of the form {plugin: 'name', options: {object}}.

grep

The regular expression, something like /\.(?:js|coffee|ls)$/, that a filename must pass to be served using browserify from a directory.

hooks

There are a number of hooks that you can implement to modify the source at a few stages of processing.

e.g.

app.get('/index.js', browserify('/index.js', {
  preminify: function (source) {
    return angularJsMinifier(source);
  }
}));

The available hooks are currently:

  • postcompile - fires after compilation, but before any minfication/gzipping
  • preminify - fires before minfication (but only if minify is enabled)
  • postminify - fires after minfication (but only if minify is enabled)

The main use case you might have for this would be adding extra minfication steps that are able to make additional assumptions about your code. These hooks can return either a string or a Promise for a string.

Others

The remaining settings are all passed through to browserify, you should look at the browserify readme if you want to know more:

  • options.external - an array of module names that will be required from external bundles (see browserify/multiple bundles) (default: [])
  • options.ignore - an aray of module names that are prevented from showing up in the output bundle (default: [])
  • options.ignoreMissing - set to true to ignore errors when a module can't be found (default: false).
  • options.transform - an array of transforms to transform top level modules (default: []). Each item can be:
    • "transform-name" - the npm name of the transform
    • transformFunction - the transform function
    • ["transform-name" | tranformFunction, {option1: true, ...}] - the transform and some options
  • options.insertGlobals - set to true to always insert process, global etc. without analysing the AST for faster builds but larger bundles (Note that options.minify may cause the globals to be removed again anyway) (default: false)
  • options.detectGlobals - set to false to skip adding process, global etc. Setting this to false may break more npm modules (default: true).
  • options.noParse - an array of module names that should not be parsed for require statements of node.js style globals, can speed up loading things like jQuery that are huge but never use require.
  • options.standalone - generate a standalone build (in a umd wrapper) with this name, you probably don't want this.
  • options.extensions - 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.
  • options.resolve - lets you override the default resolution algorithm (e.g. use browserify to compile component modules)
  • options.basedir - this shouldn't be needed as browserify-middleware already resolves to absolute paths.

You can optionally pass a single item instead of an array to any of the options that take an array.

License

MIT

If you find it useful, a donation via gittip would be appreciated.

More Repositories

1

redux-optimist

Optimistically apply actions that can be later commited or reverted.
JavaScript
779
star
2

connect-roles

Provides dynamic roles based authorisation for node.js connect and express servers.
JavaScript
751
star
3

atdatabases

TypeScript clients for databases that prevent SQL Injection
TypeScript
551
star
4

throat

Throttle a collection of promise returning functions
JavaScript
481
star
5

express-route-tester

Attempts to give you an idea of what urls will be accepted by an express route (please fork and extend it)
HTML
408
star
6

ajax

Standalone AJAX library inspired by jQuery/zepto
JavaScript
363
star
7

taxi-rank

A JSDom based Selenium Webdriver API
TypeScript
349
star
8

sync-request

Make synchronous web requests with cross platform support.
TypeScript
324
star
9

github-real-names

A plugin for Google Chrome that adds a button to toggle showing real names instead of usernames on GitHub
JavaScript
268
star
10

typescript-json-validator

Automatically generate a validator using JSON Schema and AJV for any TypeScript type.
TypeScript
227
star
11

promisejs.org

a promise website to document and promote
CSS
217
star
12

umd

Universal Module Definition for use in automated build systems
JavaScript
145
star
13

run-browser

The simplest way to run testling type tests in the browser
JavaScript
102
star
14

authentication

Modular, strongly typed, promise based, independent implementations of various authentication protocols
TypeScript
87
star
15

regexplained.co.uk

Regular Expression playgorund inspired by regexper.com and LeaVerou/regexplained
JavaScript
80
star
16

react-code-mirror

CodeMirror component for Facebook React
JavaScript
79
star
17

sync-rpc

Run asynchronous commands synchronously by putting them in a separate process
JavaScript
74
star
18

cabbie

WebDriver for the masses
JavaScript
71
star
19

react-data-fetching-demo

A demo of different ways of doing data fetching in react
JavaScript
65
star
20

react-digit-input

Higher Order Component for passcode/separated digit input.
TypeScript
61
star
21

graphql-schema-gen

Generate JavaScript GraphQL schema from the GraphQL language
JavaScript
57
star
22

ink-console

Render a scrollable terminal log in your ink app
TypeScript
57
star
23

define-form

strongly typed forms using [final-form](https://github.com/final-form/final-form)
TypeScript
49
star
24

acorn-globals

Use acorn to detect global variables in JavaScript
JavaScript
45
star
25

dehumanize-date

Parse dates in all the formats humans like to use.
JavaScript
43
star
26

stop

stop complicating your static website building
JavaScript
41
star
27

tsgen

TypeScript
40
star
28

seed-random

Generate random numbers with a seed, useful for reproducible tests
JavaScript
37
star
29

spawn-sync

Pollyfill v0.12/iojs spawnSync method
JavaScript
35
star
30

QEJS

Asyncronous Embedded JavaScript Templates with Q
JavaScript
31
star
31

redux-wait

A helper to let you wait for redux actions to be processed in a universal app.
JavaScript
30
star
32

jade-brackets

Brackets and code-mirror modes for jade
HTML
29
star
33

regexp

Regular Expression Parser in Pure JS
JavaScript
28
star
34

sync-mysql

Make synchronous queries to a mysql database
JavaScript
28
star
35

barrage

Extensions to streams (as a mixin)
TypeScript
27
star
36

closest

Find the closest parent that matches a selector
JavaScript
27
star
37

is-browser

Test whether you're a component in browser or a package in npm
JavaScript
27
star
38

legacy-encoding

Support as many legacy encodings as possible
JavaScript
25
star
39

sha

Check and get file hashes using sha1, md5 etc....
JavaScript
22
star
40

end-to-end-testing-react-applications

TypeScript
22
star
41

uglify-to-browserify

A transform to make UglifyJS work in browserify
JavaScript
21
star
42

uptime-robot

A simple node.js API for uptime robot
JavaScript
20
star
43

docker-over-ssh

đŸŗEfficiently transfer docker containers over ssh connections
TypeScript
19
star
44

cancellation

A method for making async operations cancellable
JavaScript
19
star
45

pull-request

All the tools you need to commit to GitHub repos via the API and create pull requests
JavaScript
18
star
46

rfileify

Convert any code using rfile and derivatives so that it supports browserify
JavaScript
17
star
47

unpkg-bot

JavaScript
17
star
48

halting-problem

Solves the halting problem :)
JavaScript
16
star
49

vscode-sql-template-literal

Syntax highlighting for template literals tagged as "sql" in vscode
JavaScript
16
star
50

mandate

The easy way to deploy websites to S3
JavaScript
15
star
51

supermarked

marked with syntax highlighting and LaTeX maths support
JavaScript
15
star
52

character-parser

Parse JavaScript one character at a time to look for snippets in Templates
TypeScript
15
star
53

thread-sleep

A native module for when you just need node to back off for a few milliseconds
JavaScript
13
star
54

type-assertions

Assertions to test your TypeScript types.
TypeScript
13
star
55

N1-GitHub

JavaScript
13
star
56

brackets-globals

Highlight global variables in brackets
JavaScript
13
star
57

opaque-types

Support for opaque and nominal types in typescript via a transformation.
TypeScript
13
star
58

graphql-merge-unmerge

Batch GraphQL queries by merging them and un-merging the results
TypeScript
12
star
59

code-mirror

This is now deprecated, use the official CodeMirror implementation
JavaScript
12
star
60

brcdn.org

Browserify CDN
CSS
12
star
61

typescript-for-react-developers

TypeScript
12
star
62

base64

base64 encode/decode in JavaScript
JavaScript
11
star
63

ascii-math

node.js version of http://www1.chapman.edu/~jipsen/mathml/asciimath.html
JavaScript
11
star
64

github-bot

Everything you need to build a bot for submitting automated pull requests
JavaScript
11
star
65

github-actions-workflow-builder

Build workflows for GitHub Actions using TypeScript
TypeScript
11
star
66

http-basic

low level wrapper around http.request/https.request with caching, redirects, gzip etc.
TypeScript
10
star
67

lsr

Recursive readdir (`ls -R`)
TypeScript
10
star
68

react-abstract-button

TypeScript
8
star
69

submit

form upload and progress api
JavaScript
8
star
70

deviate

Redirecting middlware for express
JavaScript
8
star
71

rfile

require a plain text or binary file in node.js
JavaScript
8
star
72

gethub

Download a github repository to a folder using the .tar.gz bundle
JavaScript
8
star
73

npm-fetch

Fetch npm modules
JavaScript
8
star
74

yieldify

Compiler for ES6 with no runtime component
JavaScript
8
star
75

ert

Express routing templates provides a simple micro-templating syntax for building strings from a template and a request object.
JavaScript
8
star
76

object-explorer

A browser module to create an extensible gui to explore objects
JavaScript
7
star
77

bulletproof-react-workshop

JavaScript
7
star
78

jwt-cache

Cache an async function for generating a JSON Web Token
TypeScript
7
star
79

testit

Because the world needs a simpler testing framework
JavaScript
7
star
80

imsave

Imgur image upload API
JavaScript
7
star
81

QJS

Use the await keyword in node.js code with Q promises.
JavaScript
7
star
82

npm-package-template

đŸ“ĻA template for npm packages built in TypeScript
JavaScript
7
star
83

base64-decode

Decode base-64 strings with JavaScript
JavaScript
6
star
84

acorn-has-side-effect

A simple module to check whether an expression has any side effects.
JavaScript
6
star
85

cssdeps

Take some CSS, figure out what files it depends on.
JavaScript
6
star
86

unescape-html

The reverse of escape-html
JavaScript
6
star
87

simple-queue-service

Simple interface to amazon's simple queue service
JavaScript
6
star
88

arrayify

Convert array like items or individual items into arrays
JavaScript
6
star
89

work-token

Simple proof of work generation and verification library based on hashcachgen
JavaScript
6
star
90

component-release

Node.js based git-release for use with component
JavaScript
6
star
91

base64-encode

Encode base-64 strings with JavaScript
JavaScript
6
star
92

svgo-unique-id

svgo plugin to generate unique IDs
JavaScript
6
star
93

interpret

An interpreter for executing un-trusted Esprima Parse Trees with powerful extensibility to aid asynchronous programming
JavaScript
6
star
94

data-action

Bind all sorts of things to html click events
JavaScript
5
star
95

stable-sha1

Get a consistent sha1 hash for a JSON object in both browser and node
JavaScript
5
star
96

babel-live

Live reloading for servers written in node.js using babel
JavaScript
5
star
97

intro-to-react

WIP React Workshop
JavaScript
5
star
98

inline-code

tools to help you inline a variety of function calls in JavaScript code
JavaScript
5
star
99

parameter-reducers

Use reducers to build type safe CLI parameter parsers
TypeScript
5
star
100

booting-nav

Fixes subnav to the top when it scrolls out of view (intended to work with bootstrap)
HTML
5
star