How to “require” text files with browserify?

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

提交回复
热议问题