How to “require” text files with browserify?

喜欢而已 提交于 2019-12-03 06:48:24

问题


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.



来源:https://stackoverflow.com/questions/17379891/how-to-require-text-files-with-browserify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!