How to “require” text files with browserify?

前端 未结 3 797
旧巷少年郎
旧巷少年郎 2021-02-02 11:19

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

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

相关标签:
3条回答
  • 2021-02-02 11:44

    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

    0 讨论(0)
  • 2021-02-02 11:44

    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.

    0 讨论(0)
  • 2021-02-02 11:47

    stringify:

    https://github.com/JohnPostlethwait/stringify

    Here's author example:

    var bundle = browserify()
        .transform(stringify(['.hjs', '.html', '.whatever']))
        .add('my_app_main.js');
    
    0 讨论(0)
提交回复
热议问题