How to "require" text files with browserify?

haimke picture haimke · Jun 29, 2013 · Viewed 18.4k times · Source

I am using browserify (using browserify-middleware) how can I require simple text files, something like:

var myTmpl = require("myTmpl.txt");

I cheked stringify plugin for browserify but the code in the documentation is not working with browserify V2

Answer

substack picture substack · Jul 6, 2013

require() is really best for just javascript code and json files to maintain parity with node and to improve readability of your code to outsiders who expect require() to work the way it does in node.

Instead of using require() to load text files, consider using the brfs transform. With brfs, you maintain parity with node by calling fs.readFileSync() but instead of doing synchronous IO as in node, brfs will inline the file contents into the bundle in-place so

var src = fs.readFileSync(__dirname + '/file.txt');

becomes

var src = "beep boop\n";

in the bundle output.

Just compile with -t brfs:

browserify -t brfs main.js > bundle.js

More discussion about why overloading require() too much is a bad idea: http://mattdesl.svbtle.com/browserify-vs-webpack