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
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.
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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With