Browserify insert global variable

血红的双手。 提交于 2019-12-07 03:06:06

问题


Despite there are a lot of relative questions, they do not answer how to resolve the following issue.

I have a nodejs file index.js.

var browserify = require('browserify');

var data = getSomeData();
browserify('entry.js').bundle();

I want so that datacould be accessed in entry.js. I found browserify option insertGlobalVars but I could not find any proper documentation or examples. I tried {insertGlobalVars: {myVar: someData}} but it does not work.

I could not call require('someData') because my data is produced only when executing index.js.

Update: Data is an array; key is a file name, value - file content (size is about 500b).


回答1:


The insertGlobalVars option takes an object that contains functions (called with file and basedir arguments). So you would have to specify your insertGlobalVars option like this:

var browserify = require('browserify');
var someData = getSomeData();

browserify('entry.js', {
    insertGlobalVars: {
        someData: function () { return JSON.stringify(someData); }
    }
})
.bundle()
.pipe(process.stdout);

Note that the data will only be included in the bundle if the someData global is actually used in the code. And each module that uses the global will receive its own copy.

It would be possible to inject an additional module into the bundle, so that the data could be required (and the bundle would contain only a single copy of the data), but that would be more complicated due to the interaction between module-deps and the file system. For more information, you could have a look at this answer.



来源:https://stackoverflow.com/questions/40173707/browserify-insert-global-variable

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