How to “require” text files with browserify?

2020-05-20 04:53发布

问题:

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

回答1:

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



回答2:

stringify:

https://github.com/JohnPostlethwait/stringify

Here's author example:

var bundle = browserify()
    .transform(stringify(['.hjs', '.html', '.whatever']))
    .add('my_app_main.js');


回答3:

If you really want to use require(), you may want to look at partialify:

my.txt:

Hello, world!

index.js:

alert( require( "my.txt" ) );

Where Browserify is configured:

var partialify = require( "partialify/custom" );
partialify.alsoAllow( "txt" );

bundle.add( "./index.js" );
bundle.transform( partialify );

Theoretically you will get a "Hello, world!" message in browser.
P.S. I haven't tried this myself.

Edit: note that this solution breaks NodeJS compatibility - it only works in browserified state, as NodeJS doesn't know how to require .txt files.