Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "require" text files with browserify?

Tags:

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

like image 992
haimke Avatar asked Jun 29 '13 11:06

haimke


People also ask

When should I use Browserify?

Browserify solves the problems of having too many JS files referenced in your HTML, inability to use Node modules in the browser, and inability to reference your own modules in your own code. Watchify streamlines the process of bundling your files and will make a change every time you change a JS file in your project.

How do I use Browserify bundles?

Bundle up your first module js does. With Browserify you can write code that uses require in the same way that you would use it in Node. Browserify parses the AST for require() calls to traverse the entire dependency graph of your project. Drop a single <script> tag into your html and you're done!

Is Browserify a dev dependency?

We can also include browserify itself as a dependency, however it isn't a dependency for the project to run – any user to our app can find Superman without needing to run Browserify. It is one of our devDependencies – modules required for developers to make updates to this app. Now we've got a package.


1 Answers

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

like image 200
substack Avatar answered Oct 21 '22 21:10

substack