Browser insert global variable

Despite many relative questions, they do not answer how to solve the following problem.

I have a nodejs index.js file.

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

I want data be available in entry.js . I found the browser option insertGlobalVars , but I could not find any suitable documentation or examples. I tried {insertGlobalVars: {myVar: someData}} but it does not work.

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

Update : Data is an array; key is the name of the file, value is the contents of the file (size about 500b).

+5
source share
1 answer

The insertGlobalVars parameter accepts an object that contains functions (called with file and basedir arguments). Therefore, you will need to specify your insertGlobalVars parameter as follows:

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

Please note that data will only be included in the package if someData global is actually used in the code. And each module that uses the global will get its own copy.

One could add an additional module to the bundle so that the data could be needed (and the bundle would contain only one copy of the data), but this would be more complicated due to the interaction between module-deps and the file system. For more information you can see this answer .

+5
source

Source: https://habr.com/ru/post/1258598/


All Articles