Git Product home page Git Product logo

brfs'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!

brfs's People

Contributors

deathcap avatar denis-sokolov avatar feross avatar forivall avatar goto-bus-stop avatar hubdotcom avatar jagonzalr avatar juliangruber avatar mattdesl avatar paulirish avatar pirxpilot avatar rgbboy avatar stevemao 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

brfs's Issues

remove require('fs') unless used else where

It would be handy to remove require('fs') calls from a file, if it is not used for anything else but fs.readFile....

This way, there is no need to to include a fs shim in the application.

upgrading 1.0.2 -> 1.1.0 throws parse errors

when I rely on [email protected] my bundle builds correctly. As soon as I upgrade to 1.1.0 or higher, I start seeing these errors generated:

ฮป npm run watchify

> [email protected] watchify /Users/mike/web
> watchify js/wrapp.coffee -v --extension .js --extension .coffee -o  js/wrapp.js

Error: Parsing file /Users/mike/web/js/models/audit-log.coffee: Line 2: Unexpected identifier
Error: Parsing file /Users/mike/web/js/models/banner.coffee: Line 2: Unexpected identifier
Error: Parsing file /Users/mike/web/js/models/user.coffee: Line 3: Unexpected identifier

here's the relevant fields in my package.json:

"dependencies": {
    "brfs": "1.1.0",
    "browserify": "^3.44.1",
    "browserify-shim": "^3.4.1",
    "coffeeify": "^0.6.0",
    "watchify": "0.8.1"
  },
"scripts": {
    "watchify": "watchify js/wrapp.coffee -v --extension .js --extension .coffee -o assets/javascripts/wrapp.js",
    "browserify": "browserify js/wrapp.coffee --extension .js --extension .coffee -o assets/javascripts/wrapp.js",
  },
"browserify": {
    "transform": [ "coffeeify", "brfs" ]
  }

Any ideas why these errors might occur?

Cannot switch to old mode now

I'm getting this error on anything I try to run brfs with:

_stream_readable.js:730
    throw new Error('Cannot switch to old mode now.');
          ^
Error: Cannot switch to old mode now.
    at emitDataEvents (_stream_readable.js:730:11)
    at ReadStream.Readable.resume (_stream_readable.js:715:3)
    at Object.<anonymous> (/usr/local/lib/node_modules/brfs/bin/cmd.js:21:4)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

Testcase: https://github.com/MatthewMueller/cheerio-select/blob/master/index.js

Node 0.10.17

convert all .html files strings in to a single js file.

I am trying to convert all .html template files in to a single bundle.js file by reading file content from each .html file.

I tried like this: (not working)

var fs = require('fs');
var __view = 'app/templates';
var templateFiles = fs.readDir(__view);
var obj = {};
for(var i = 0; i < templateFiles.length; i++){
    obj[i] = fs.readFileSync(__view + templateFiles[i], 'utf8');
}
console.log(obj);

I want bundle.js to have that obj object.

UPDATE:

I am converting statically by writing the following code in main.js

var fs = require('fs');
var templates = {
    'header': fs.readFileSync('app/templates/header.html', 'utf8'),
    'heading': fs.readFileSync('app/templates/heading.html', 'utf8')
}

This is working but adding some unnecessary wrapper functions in bundle.js when I run browserify -t brfs main.js > bundle.js in cmd:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

var templates = {
    'header': "<div class=\"headerSection\">\r\n\t<div class=\"headerSectionWrapper\">\r\n\t\t<div class=\"logo\">{{name}}</div>\r\n\t\t<div class=\"searchBarSection\">\r\n\t\t\t<div class=\"searchBar\">\r\n\t\t\t\t\r\n\t\t\t</div>\r\n\t\t\t<div class=\"searchTextHolder\">\r\n\t\t\t\t<form name=\"searchform\">\r\n\t\t\t\t\t<input type=\"text\" name=\"searchbox\"></input>\r\n\t\t\t\t</form>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t</div>\r\n</div>",
    'heading': "<!-- HTML Template -->\n<h3>heading</h3>\n"
}
},{}]},{},[1]);

How to remove this wrapper functions? and is there any way to add a watch expression. so that I can see instant update in bundle.js when I change any .html files ?

var foo = require('bar'), fs = require('fs'); doesn't parse

gareth@samson:~/Documents/davinci$ make
./node_modules/.bin/browserify -t brfs ./lib/index.js > ./davinci.js
SyntaxError: Line 2: Unexpected string while parsing /home/gareth/Documents/davinci/lib/template/index.js
    at Stream.end (/home/gareth/Documents/davinci/node_modules/browserify/node_modules/insert-module-globals/index.js:71:21)
    at _end (/home/gareth/Documents/davinci/node_modules/browserify/node_modules/insert-module-globals/node_modules/through/index.js:65:9)
    at Stream.stream.end (/home/gareth/Documents/davinci/node_modules/browserify/node_modules/insert-module-globals/node_modules/through/index.js:74:5)
    at DuplexWrapper.onend (/home/gareth/Documents/davinci/node_modules/brfs/node_modules/static-module/node_modules/duplexer2/node_modules/readable-stream/lib/_stream_readable.js:530:10)
    at DuplexWrapper.g (events.js:199:16)
    at DuplexWrapper.EventEmitter.emit (events.js:129:20)
    at /home/gareth/Documents/davinci/node_modules/brfs/node_modules/static-module/node_modules/duplexer2/node_modules/readable-stream/lib/_stream_readable.js:927:16
    at process._tickCallback (node.js:343:11)
make: *** [davinci.js] Error 1

Fixed by moving the call to require('fs') onto its own line.

Error: write after end

I wrote a gulp task using this article:

var browserified = transform(function(filename) {
    var b = browserify(filename);
    b.transform('brfs');
    return b.bundle();
});


return gulp.src(src)
    .pipe(browserified)
    .pipe(uglify())
    .pipe(gulp.dest(dest));

When I run this, I get an error: Error: write after end at writeAfterEnd (/www/my-project/node_modules/browserify/node_modules/labeled-stream-splicer/node_modules/stream-splicer/node_modules/readable-stream/lib/_stream_writable.js:161:12)

If I comment out the b.transform('brfs');, everything works fine. Does anyone have any insight as to why this is happening?

Thanks!

Does not work with browserify -r option

Below is my test.js :

var fs = require('fs');
var html = fs.readFileSync(__dirname + '/widget.html', 'utf8');
module.exports = Test;
function Test () {};

Use brfs without -r :

browserify -t brfs ./test.js

will get correctly compiled string :

var html = "<form class=\"send\">\n  <textarea type=\"text\" name=\"msg\"></textarea>\n  <input type=\"submit\" value=\"submit\">\n</form>";

But use with -r :

browserify -t brfs -r ./test.js:test 

fs code will not be compiled :

var html = fs.readFileSync(__dirname + '/widget.html', 'utf8');

Support fs.createReadStream?

A module I'm using (parse-obj by @mikolalysenko) expects an incoming data stream, which I am loading from a static asset using brfs. But since there is no direct support for createReadStream I have been needing to add a simple Readable wrapper on top of readFile. It's not a huge problem, but I wonder if that boilerplate can be baked into brfs itself... I can do a quick PR if there are no design/scope issues with that.

Still maintained?

Hi before using this, I was wondering if this project is still maintained? If not, I will have a look for another alternative.

Kind regards

require('./some.html') causing error

I am using partialify to parse my HTML partials with simple require()'s, but if brfs is in the transform list before partialify it throws an error like this

[Error: Line 1: Unexpected token < (/path/to/template.html)]

Shouldn't brfs only be parsing fs.readFileSync() calls?

Fails on Multiple Inlines

A single inline works fine, but multiple inlines do not:

var fs = require('fs').readFileSync(__dirname+'/index.js')
var fs2 = require('fs').readFileSync(__dirname+'/package.json')
console.log(fs)

brfs chokes on #! /usr/bin/env node

When I browserify JSONStream, the line #! /usr/bin/env node, causes brfs to throw an error.

Works fine without the brfs transform.

C:\Users\Michael\Github\javascript\convert-and-seed-audio>browserify node_modules/JSONStream -t brfs -o deleteme.js
SyntaxError: Unexpected character '#' (1:0)
    at Parser.pp.raise (C:\Users\Michael\Github\javascript\convert-and-seed-audio\node_modules\brfs\node_modules\static-module\node_modules\falafel\node_modules\acorn\dist\acorn.js:1745:13)
    at Parser.pp.getTokenFromCode (C:\Users\Michael\Github\javascript\convert-and-seed-audio\node_modules\brfs\node_modules\static-module\node_modules\falafel\node_modules\acorn\dist\acorn.js:3486:8)
    at Parser.pp.readToken (C:\Users\Michael\Github\javascript\convert-and-seed-audio\node_modules\brfs\node_modules\static-module\node_modules\falafel\node_modules\acorn\dist\acorn.js:3189:15)
    at Parser.pp.nextToken (C:\Users\Michael\Github\javascript\convert-and-seed-audio\node_modules\brfs\node_modules\static-module\node_modules\falafel\node_modules\acorn\dist\acorn.js:3181:71)
    at parse (C:\Users\Michael\Github\javascript\convert-and-seed-audio\node_modules\brfs\node_modules\static-module\node_modules\falafel\node_modules\acorn\dist\acorn.js:100:5)
    at module.exports (C:\Users\Michael\Github\javascript\convert-and-seed-audio\node_modules\brfs\node_modules\static-module\node_modules\falafel\index.js:22:15)
    at C:\Users\Michael\Github\javascript\convert-and-seed-audio\node_modules\brfs\node_modules\static-module\index.js:37:23
    at ConcatStream.<anonymous> (C:\Users\Michael\Github\javascript\convert-and-seed-audio\node_modules\brfs\node_modules\static-module\node_modules\concat-stream\index.js:36:43)
    at ConcatStream.emit (events.js:129:20)
    at finishMaybe (C:\Users\Michael\Github\javascript\convert-and-seed-audio\node_modules\brfs\node_modules\static-module\node_modules\concat-stream\node_modules\readable-stream\lib\_stream_writable.js:460:14)

C:\Users\Michael\Github\javascript\convert-and-seed-audio>browserify node_modules/JSONStream -o deleteme.js

C:\Users\Michael\Github\javascript\convert-and-seed-audio>

I am using browserify on a project that uses brfs and JSONStream, so I would like them to play nice together.

Using [email protected].

Can this be used if the fs call is within a function?

I have the following code (shortened and simplified)

function load(path) {
fs.readFileSync(path);
}

that is called a few times throughout this module to synchronously load dependencies. Will this plugin be able to handle these kind of calls? Thanks

Works only on first-level includes

Using -t brfs works for source directly in a module, but if require'd modules use fs.readFileSync calls, brfs doesn't find and transform them unless you specify -r moduleName, and if require'd modules require modules that in turn use fs.readFileSync, that trick no longer works and it's not clear that there's any way to make the transform apply.

So, like:

csv2geojson can -r dsv to apply the transform on its dependency when it is browserified to a standalone, but

geojson.io cannot make sure that dsv (through csv2geojson) is brfs'ed at all.

Long string in file breaking brfs

The following works now:

var fs = require('fs'),
  a = fs.readFileSync(__dirname + '/foo.txt', 'utf8'),
  b = fs.readFileSync(__dirname + '/bar.txt', 'utf8');

console.log(a, b)

The following does not work:

var c = "# devtool\n\n[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges)\n\n\n\n## Usage\n\n[![NPM](https://nodei.co/npm/devtool.png)](https://www.npmjs.com/package/devtool)\n\n## License\n\nMIT, see [LICENSE.md](http://github.com/Jam3/devtool/blob/master/LICENSE.md) for details.\n";
var fs = require('fs'),
  a = fs.readFileSync(__dirname + '/foo.txt', 'utf8'),
  b = fs.readFileSync(__dirname + '/bar.txt', 'utf8');

console.log(a, b)

Not sure exactly what part of that string is breaking things.

Error combining with 6to5ify

I'm trying to do a brfs transform after 6to5ify, but get the following error.

browserify()
    .require("main", { entry: true })
    .transform(6to5ify)
    .transform(brfs)
    .bundle()
    .pipe(fs.createWriteStream(path.join('app.js')));
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: tried to statically call { readFile: [Function: readFile], readFileSync: [Function: readFileSync], readdir: [Function: readdir], readdirSync: [Function: readdirSync] } as a function while parsing file: /Users/akula/foo/main.js while parsing file: /Users/akula/foo/main.js
    at error (/Users/akula/foo/node_modules/brfs/node_modules/static-module/index.js:71:49)
    at traverse (/Users/akula/foo/node_modules/brfs/node_modules/static-module/index.js:247:24)
    at walk (/Users/akula/foo/node_modules/brfs/node_modules/static-module/index.js:216:13)
    at walk (/Users/akula/foo/node_modules/brfs/node_modules/static-module/node_modules/falafel/index.js:60:9)
    at /Users/akula/foo/node_modules/brfs/node_modules/static-module/node_modules/falafel/index.js:51:25
    at Array.forEach (native)
    at forEach (/Users/akula/foo/node_modules/brfs/node_modules/static-module/node_modules/falafel/index.js:8:31)
    at /Users/akula/foo/node_modules/brfs/node_modules/static-module/node_modules/falafel/index.js:49:17
    at Array.forEach (native)
    at forEach (/Users/akula/foo/node_modules/brfs/node_modules/static-module/node_modules/falafel/index.js:8:31)

btw, there's a double "while parsing file" in the message.

My main.js looks like this.

import fs from 'fs';

var foo = fs.readFileSync(__dirname + '/foo.html');
console.log(foo.toString());

If I change the import to a require and don't do 6to5ify it works fine, but together it gives the error.

Deduplicating modules requiring the same files

When I use require to load some json, if I use this file in different modules, browserify compiles the json file into the built script twice, there needs to be a way to deduplicating brfs files just like normal require scripts.

Valid syntax is wrongly parsed

The following valid code fails to parse when brfs is used within a browserify transform:

css.js:

var
    /**
     * Dependencies.
     */
    fs = require('fs'),

    /**
     * Local variables.
     */
    style = fs.readFileSync(__dirname + '/assets/css/style.css', 'utf8');


module.exports = function () {
    var
        tag = document.createElement('style'),
        content = document.createTextNode(style);

    tag.appendChild(content);
    document.body.appendChild(tag);
};

When running a gulp task as follows it fails:

gulp.task('browserify', function () {
    return browserify([path.join(__dirname, PKG.main)], {
        standalone: PKG.name
    })
        .transform('brfs')
        .bundle()
        .pipe(vinyl_source_stream(PKG.name + '.js'))
        .pipe(filelog('browserify'))
        .pipe(gulp.dest('dist/'));
});

Output:

[11:44:01] 'browserify' errored after 198 ms
[11:44:01] Error:
/Users/ibc/src/someapp/lib/css.js:4
module.exports = function () {
      ^
ParseError: Unexpected token
    at formatError (/Users/ibc/.npm-packages/lib/node_modules/gulp-cli/lib/versioned/^4.0.0-alpha.1/formatError.js:20:10)
    at Gulp.<anonymous> (/Users/ibc/.npm-packages/lib/node_modules/gulp-cli/lib/versioned/^4.0.0-alpha.1/log/events.js:26:15)
    at Gulp.emit (events.js:107:17)
    at Object.error (/Users/ibc/src/someapp/node_modules/gulp/node_modules/undertaker/lib/helpers/createExtensions.js:58:10)
    at handler (/Users/ibc/src/someapp/node_modules/gulp/node_modules/undertaker/node_modules/bach/node_modules/now-and-later/lib/mapSeries.js:43:14)
    at f (/Users/ibc/src/someapp/node_modules/gulp/node_modules/undertaker/node_modules/bach/node_modules/now-and-later/node_modules/once/once.js:17:25)
    at f (/Users/ibc/src/someapp/node_modules/gulp/node_modules/undertaker/node_modules/bach/node_modules/async-done/node_modules/once/once.js:17:25)
    at done (/Users/ibc/src/someapp/node_modules/gulp/node_modules/undertaker/node_modules/bach/node_modules/async-done/index.js:26:12)
    at Domain.onError (/Users/ibc/src/someapp/node_modules/gulp/node_modules/undertaker/node_modules/bach/node_modules/async-done/index.js:34:12)
    at Domain.g (events.js:199:16)
  • brfs 1.4.0
  • browserify 10.2.4

Does not work in single var statement defining multiple variables

The example provided in the README works fine, but the following does not:

var fs = require('fs'),
    html = fs.readFileSync('./robot.html', 'utf8');
console.log(html);

// Compiled to:
var html = fs.readFileSync('./robot.html', 'utf8');
console.log(html);

I am not sure if this is a browserify limitation or an actual bug though.

Does not work with var fs = require('fs'), uninitialized;

The following construct:

var fs = require('fs'), 
    uninitialized;

Fails with the following error:

$ browserify -t brfs test.js 
TypeError: Cannot read property 'start' of null while parsing file: test.js
    at node_modules/static-module/index.js:120:56
    at Array.forEach (native)
    at walk (node_modules/static-module/index.js:112:22)
    at walk (node_modules/falafel/index.js:49:9)
    at node_modules/falafel/index.js:46:17
    at forEach (node_modules/foreach/index.js:12:16)
    at walk (node_modules/falafel/index.js:34:9)
    at node_modules/falafel/index.js:41:25
    at forEach (node_modules/foreach/index.js:12:16)
    at node_modules/falafel/index.js:39:17

Changing the declaration to:

var fs = require('fs'),
    uninitialized = undefined;

solves the problem:

$ browserify -t brfs test.js 
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var uninitialized = undefined;

},{}]},{},[1]);

I'll submit a pull request to static-module to fix this.

Handle failure for readFileSync

In node I can wrap a call to readFileSync in a synchronous try/catch:

var fs = require('fs');

try {
  fs.readFileSync('./does/not/exist');
} catch (e) {
  console.log('caught!');
}

and running it will write caught! but running through browserify -t brfs gives

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: ENOENT, open './does/not/exist'

Is there a way that the same thing with brfs? I know that brfs processes the source statically, but I'm doing things like running the source through envify first and the fs call could fail and stop the build. Probably does so for the best, but I was wondering if there is a way to inline an empty string, undefined, etc.

Thanks substack!

Random "Unexpected token ILLEGAL" error

I'm having some trouble pinpointing the exact cause of this error, but I've got 4 bundles and only the one with readFileSync calls fails randomly with this error. In that bundle, there are 7 readFileSync calls in succession. I added some logging and it seems that when this error triggers, the source is mangled and the readFileSync calls are resolved out of order. It only happens once out of 20 or so times.

I'd be happy to debug further, but I'm not sure where to look next or what information you might need.

Dynamic use of fs.readFileSync in server-side only codepath causes build failure

I have shared code that reads some files on the server to hash them, but the file reading code is unreachable on the client.
The code needs to be sync, thus the usage of readFileSync.
The results are cached so the performance impact of the sync call can be ignored.

This causes browserify bundling to fail with the error
Error: ReferencefilesystemPath is not defined (/path/to/file)

If the path is undefined, browserify should skip inlining the file instead of crashing.
Another option would be to add a way to mark portions of the code as server-side only and skip those for source transforms.

readdirSync not showing the correct results after file changes

The first time I do fs.readdirSync it gives me the correct result. After I delete one file and use chokidar to trigger this unlink event fs.readdirSync still gives me the same results. Is this the correct behavior? If yes, is there anyway I can get the updated list of files? Thanks.

Usage from grunt-browserify not working

I tried to use it from grunt but when i require 'fs' start getting the following error:

TypeError: Cannot read property 'range' of null

Any idea where doe it come from?

brfs + mime

not sure if this belongs in brfs or mime issues queues...

brfs is not replaceing an instance of fs.readFileSync in mime at all.

Steps to reproduce:

  • in a new directory
  • npm install mime
  • cd node_modules/mime
  • browserify -t brfs mime.js -o temp.js (check, still contains readFileSync)
  • also, to narrow it down - i have tried 'brfs mime.js' on its own.

Im not really sure where to start debugging this - I've tracked through a number of files and its all pretty simple.

unsupported type for static module: VariableDeclarator

when running browserify js/pre-bro.app.js using brfs, I receive the following error:

Error: unsupported type for static module: VariableDeclarator
at expression:

  fs
 while parsing file: /Users/me/dev/git/studio-module-media/js/pre-bro.app.js
  at traverse (/Users/me/dev/git/studio-module-media/node_modules/brfs/node_modules/static-module/index.js:285:25)

I have determined that the lines from the source file that trigger this error are the following:

...
// Generated by CoffeeScript 1.8.0
(function() {
  var $, Definition, Marionette, QuickPublishView, Studio, Template, fs, _;

  $ = require('jquery');

  _ = require('underscore');

  fs = require('fs');
....

I'm having trouble figuring out what's going on

path.join() issues

I'm not sure what path.join() does under the hood, but afaik the following code should work:

var fs = require('fs');
var logo = fs.readFileSync(path.join(__dirname, '/playbutton.svg'), 'utf8')

Except it doesn't. This however, does:

var fs = require('fs');
var logo = fs.readFileSync(__dirname + '/playbutton.svg', 'utf8')

The stack trace just returns at Error (native) so that's not helpful. Any idea why this doesn't work? Is it intentional?

edit: actually it doesn't throw an error, my mistake. It removes the fs.readFileSync(), but doesn't replace it with the stringified resource. Running 0.11.13.

Error: unsupported type for static module: VariableDeclarator

Getting this error both in brfs 1.1.0 and 1.1.1. I'm on Windows 7, 64-bit.

I'm building my browserify bundle from the command line, using the -t brfs flag. I don't even have any require('fs') statements in my code yet; this error is thrown regardless, due to the transform.

The error is not thrown on 1.0.2 and older versions.

glob.sync woes...

Let me know if this isn't the appropriate way of requesting some guidance and/or if I'll find the answer in the browserify handbook...

I'm basically requiring this module (https://www.npmjs.com/package/countryjs)

somewhat shallowly deep, tries to glob for some json files (it's country meta data) via glob.sync

I get that brfs specifically supports fs.* but am I basically at a loss for using browserify for modules that happen to use glob?

Thanks in advance.

Error when encountering LINE_SEPARATOR

brfs causes browserify to throw an error with message "Unterminated string constant" when a file is read that contains a LINE_SEPARATOR (U+2028) character.

fs.readFileSync(filename); is ignored.

The filename argument passed by variable seems to make brfs ignore the declaration regardless of whether the path contained within the variable is valid or not.

Calling browserify -t brfs test.js -o bundle.js on test.js containing the lines below doesn't have any effect and no error is displayed until an attempt to run on client-side.

var fs = require('fs'),
    path = 'test.html',
    html = fs.readFileSync(path);

Works well in case of html = fs.readFileSync('test.html');.

I guess bf45b3a is to blame. Any ideas?

Trouble with getting brfs to inline shader scripts

I'm having trouble getting a particular file to work with the example code:

var browserify = require('browserify');
var fs = require('fs');

var b = browserify('./index.js');
b.transform('brfs');

b.bundle().pipe(fs.createWriteStream('bundle.js'));

Using the command, browserify -t brfs index.js > bundle.js , doesn't produce the desired results, either.

The error seen is:

Uncaught TypeError: Object # has no method 'readFileSync'

brfs is supposed to manage that, right?

This is the particular file in question:
https://github.com/mikolalysenko/ao-shader/blob/master/aoshader.js

I'm then simply running that script by: node build

Versions

  • node: v0.10.12
  • browserify: v2.17.4 (I'm intentionally using an older version until a bug in newer versions can be fixed)
  • brfs: v0.0.6

brfs breaks source maps

I love brfs, but this issue is right now my number one annoyance. To replicate this, take any multifile bundle and add an fs.readSync with brfs. Open up the result in chrome, and you get a single giant blob.

Any ideas on what could be done to fix this situation?

support fs.readdir and fs.readdirSync

I think this is feasible, and I personally think this is really useful.

In node.js it's reasonably common for me to do things like:

// controllers/index.js
'use strict';
var fs = require('fs');
var path = require('path');

var ROOT_PATH = __dirname;

module.exports = function(path) {
  var fnames = fs.readdirSync(ROOT_PATH);

  var paths = fnames.map(function(fname) {
    return path.join(ROOT_PATH, fname, '.js');
  });

  var modules = paths.map(function(path) {
    return require(path);
  });

  return modules.map(function(module) {
    // do something with the module
    // i.e. if it's this is a mongoose schema bootstrapping utility, register the model.
    //       if this is a express controller bootstrapping utility, parse its methods and register
   //        matching routes.
   //        etc.
  });
};

This allows us to abstract whole parts of the code, later on - even treat them as completely separate modules:

// app.js
var controllers = require('./controllers')

// bootstrap the controllers
controllers(/* something would come here such as an express app or a mongoose.Connection */);

If we could do this with browserify, things like bootstrapping an Ember app, could be automated. I know there are a couple of problems.

Here's an analogous example that works, though not exactly as one would hope it'd.

I know this has to do with limitations on the browserify module (which may be impossible to address) but this would be really cool.

Perhaps we could even parse things like:

['./a', './b'].map(function(name) {
  return require(name);
});

Into:

[require('./a'), require('./b')];

Or provide an utility requireMap thing that resolved into that.

I don't know if this is a relevant issue. But I though this would be a nice thing, if it was possible.

At it's core, the main point was simply to add:

var fs = require('fs');
var files = fs.readdirSync('.');

To be transformed into:

var fs = require('fs');
var files = ['a.js', 'b.js', 'main.js' /* etc. */];

What do you think?

fs.readFileSync() => bundleFile()?

More a suggestion than an issue. I know fs,readFileSync() from node, but bundling a file with brfs does something very different from blocking & reading a file at point of execution like fs.readFileSync(). Maybe it would be simpler to use a name that better indicates what's happening?

Just a thought. Thanks for browserify Substack! ๐Ÿค–

Doesn't handle inline required fs

Many modules are lazy and does this. Would be useful if brfs could handle it.

This doesn't work:

require('fs').readFileSync(__dirname + '/package.json', 'utf8');

This does:

var fs = require('fs');
fs.readFileSync(__dirname + '/package.json', 'utf8');

Fatal error: Cannot find module './lib/_stream_transform.js'

Fatal error: Cannot find module './lib/_stream_transform.js'
    Error: Cannot find module './lib/_stream_transform.js'
      at Function.Module._resolveFilename (module.js:336:15)
      at Function.Module._load (module.js:278:25)
      at Module.require (module.js:365:17)
      at require (module.js:384:17)
      at Object.<anonymous> (/Users/chetcorcos/code/web-ux/node_modules/brfs/node_modules/through2/node_modules/readable-stream/transform.js:1:80)
      at Module._compile (module.js:460:26)
      at Object.Module._extensions..js (module.js:478:10)
      at Module.load (module.js:355:32)
      at Function.Module._load (module.js:310:12)
      at Module.require (module.js:365:17)
      at require (module.js:384:17)
      at Object.<anonymous> (/Users/chetcorcos/code/web-ux/node_modules/brfs/node_modules/through2/through2.js:1:79)
      at Module._compile (module.js:460:26)
      at Object.Module._extensions..js (module.js:478:10)
      at Module.load (module.js:355:32)
      at Function.Module._load (module.js:310:12)
      at Module.require (module.js:365:17)
      at require (module.js:384:17)
      at Object.<anonymous> (/Users/chetcorcos/code/web-ux/node_modules/brfs/node_modules/static-module/index.js:4:15)
      at Module._compile (module.js:460:26)
      at Object.Module._extensions..js (module.js:478:10)
      at Module.load (module.js:355:32)
      at Function.Module._load (module.js:310:12)
      at Module.require (module.js:365:17)
      at require (module.js:384:17)
      at Object.<anonymous> (/Users/chetcorcos/code/web-ux/node_modules/brfs/index.js:1:82)
      at Module._compile (module.js:460:26)
      at Object.Module._extensions..js (module.js:478:10)
      at Module.load (module.js:355:32)
      at Function.Module._load (module.js:310:12)
      at Module.require (module.js:365:17)
      at require (module.js:384:17)
      at nr (/Users/chetcorcos/code/web-ux/node_modules/grunt-browserify/node_modules/browserify/node_modules/module-deps/index.js:280:21)
      at /Users/chetcorcos/code/web-ux/node_modules/grunt-browserify/node_modules/browserify/node_modules/module-deps/node_modules/resolve/lib/async.js:44:21
      at ondir (/Users/chetcorcos/code/web-ux/node_modules/grunt-browserify/node_modules/browserify/node_modules/module-deps/node_modules/resolve/lib/async.js:187:31)
      at /Users/chetcorcos/code/web-ux/node_modules/grunt-browserify/node_modules/browserify/node_modules/module-deps/node_modules/resolve/lib/async.js:153:39
      at onex (/Users/chetcorcos/code/web-ux/node_modules/grunt-browserify/node_modules/browserify/node_modules/module-deps/node_modules/resolve/lib/async.js:93:22)
      at /Users/chetcorcos/code/web-ux/node_modules/grunt-browserify/node_modules/browserify/node_modules/module-deps/node_modules/resolve/lib/async.js:24:18
      at FSReqWrap.oncomplete (fs.js:99:15)

Supporting statSync?

I ran into an issue when trying to use node-config with browserify. It seems to use statSync to check if file exists and only after that read file with readFileSync.

I was wondering if supporting statSync would fit into the scope of this project?

Inline of html files is failing

I am using browserify along with the brfs plugin to inline html. Following the example from the knockout site on using this technique: http://knockoutjs.com/documentation/component-loaders.html

There are about 20 components and the html files are just snippets. All has been working well until the last bits of an html file are not getting added all of a sudden and causing 'unterminated string constant'.

At first I thought there may be a hidden char in one of the html files but the issue happens with or with out the most recently added file.

Here is the gulp file code for my scripts task:

gulp.task('scripts', function () {
return browserify({
//set entry point into application
entries: './Client/jsbootstrapper.js',
//debug enables source maps
debug: debug
})
.bundle()
//use vinyl-source-stream to output it all to a stream
.pipe(source(scriptOutput))
//have to buffer it for uglify
.pipe(gulpif(!debug, buffer()))
//uglify
.pipe(gulpif(!debug, uglify()))
.pipe(brfs())
//pipe the stream to its destination
.pipe(gulp.dest('./'));
});

All my component registrations look like this:
ko.components.register('login-view', {
viewModel: require('./login-view/LoginViewModel.js'),
template: require('fs').readFileSync('./Client/login-view/login-view.html', 'utf8')
});

unterminatedstring

I am at a loss for any more insight as there is no problem building the output. The unterminated string blows up the browser => Uncaught SyntaxError: Unexpected token ILLEGAL

Thanks for any insight.

support require.resolve

As an example I currently have this code:

// TODO: a bit brittle if jsoneditor is deduped for instance
var css = fs.readFileSync(__dirname + '/../node_modules/jsoneditor/jsoneditor.css');
loadCSS(css);

The below would be a lot less brittle:

var css = fs.readFileSync(require.resolve('jsoneditor') + '/jsoneditor.css');
loadCSS(css);

Just checking if this is in scope and discuss best way to make this work.
I'll jump at implementing and PRing this feature if you agree that this makes sense.

fs is not defined error when readFileSync is passed a path variable

I'm getting the following error when I run this with the brfs transform.

var temp = fs.readFileSync(template_path, 'utf8');
           ^
ReferenceError: fs is not defined
...

Test 1:

var fs  = require('fs');
var temp = fs.readFileSync('./templates/test.html', 'utf8');
console.log(temp);

If I run this with node test.js, or

browserify test.js -o output.js -t brfs
node output.js

I get the expected 'hello world' content from test.html output to the console.
The contents of output.js looks like this:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

/* Test 1 */
var temp = "hello world";
console.log(temp);

},{}]},{},[1]);

However if I do the same with Test 2:

var fs  = require('fs');
var template_path = './templates/test.html';
var temp = fs.readFileSync(template_path, 'utf8');
console.log(temp);

node test.js works fine but running browserify and then node output.js gives me the fs is not defined error.
Also output now looks like this:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

/* Test 2 */

var template_path = './templates/test.html';
var temp = fs.readFileSync(template_path, 'utf8');
console.log(temp);

},{}]},{},[1]);

Support dynamic require

Many modules uses require to dynamically load JSON files.

Example:

require('./path/' + name + '.json');

Failing to browserify parsers generated by Jison

$ ls
calc.jison
$ cat calc.jison 
/* description: Parses end executes mathematical expressions. */

/* lexical grammar */
%lex

%%
\s+                   /* skip whitespace */
[0-9]+("."[0-9]+)?\b  return 'NUMBER';
"*"                   return '*';
"/"                   return '/';
"-"                   return '-';
"+"                   return '+';
"^"                   return '^';
"("                   return '(';
")"                   return ')';
"PI"                  return 'PI';
"E"                   return 'E';
<<EOF>>               return 'EOF';

/lex

/* operator associations and precedence */

%left '+' '-'
%left '*' '/'
%left '^'
%left UMINUS

%start expressions

%% /* language grammar */

expressions
    : e EOF
        {print($1); return $1;}
    ;

e
    : e '+' e
        {$$ = $1+$3;}
    | e '-' e
        {$$ = $1-$3;}
    | e '*' e
        {$$ = $1*$3;}
    | e '/' e
        {$$ = $1/$3;}
    | e '^' e
        {$$ = Math.pow($1, $3);}
    | '-' e %prec UMINUS
        {$$ = -$2;}
    | '(' e ')'
        {$$ = $2;}
    | NUMBER
        {$$ = Number(yytext);}
    | E
        {$$ = Math.E;}
    | PI
        {$$ = Math.PI;}
    ;
$ npm install browserify brfs jison
[...]
$ node_modules/.bin/jison calc.jison 
$ node_modules/.bin/browserify calc.js -o bundle.js
$ node_modules/.bin/browserify calc.js -o bundle.js -t brfs
TypeError: Object #<Object> has no method 'apply' while parsing file: /tmp/test/calc.js
    at walk (/tmp/test/node_modules/brfs/node_modules/static-module/node_modules/static-eval/index.js:89:27)
    at walk (/tmp/test/node_modules/brfs/node_modules/static-module/node_modules/static-eval/index.js:92:23)
    at walk (/tmp/test/node_modules/brfs/node_modules/static-module/node_modules/static-eval/index.js:77:26)
    at walk (/tmp/test/node_modules/brfs/node_modules/static-module/node_modules/static-eval/index.js:85:25)
    at module.exports (/tmp/test/node_modules/brfs/node_modules/static-module/node_modules/static-eval/index.js:114:7)
    at traverse (/tmp/test/node_modules/brfs/node_modules/static-module/index.js:256:23)
    at walk (/tmp/test/node_modules/brfs/node_modules/static-module/index.js:208:13)
    at walk (/tmp/test/node_modules/brfs/node_modules/static-module/node_modules/falafel/index.js:49:9)
    at /tmp/test/node_modules/brfs/node_modules/static-module/node_modules/falafel/index.js:46:17
    at forEach (/tmp/test/node_modules/brfs/node_modules/static-module/node_modules/falafel/node_modules/foreach/index.js:12:16)
$ 

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.