How to “require” text files with browserify?

前端 未结 3 801
旧巷少年郎
旧巷少年郎 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

    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.

提交回复
热议问题