Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browserify insert global variable

Tags:

browserify

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).

like image 392
FreeLightman Avatar asked Oct 21 '16 10:10

FreeLightman


1 Answers

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.

like image 67
cartant Avatar answered Oct 15 '22 05:10

cartant