简体   繁体   中英

browserify two separate bundles pass variable from second file

main.js
level.js
 num3.js
 num4.js

main.js looks like below

require('./level');
console.log(num3);  

level.js looks like below

var num3 = require('./num3');
var num4 = require('./num4');

bundled files

browserify --require ./level.js:level.js > bundle-level.js
browserify --exclude level.js main.js > bundle-main.js

I'm unable to get num3 //Uncaught ReferenceError: num3 is not defined variable which required from ./num3 also num4 , if I change var num3 = require('./num3'); to global variable window.num3 = require('./num3'); is fine to get values.

Is there a proper way to have variables num3 and num4 passed through?

First, I think there is an issue with the require in main.js .

If main.js has this require :

require('./level');

Browserify will be including level.js in the main bundle. The reason is that the name that follows the : in this command:

browserify --require ./level.js:level.js > bundle-level.js

is the name that's used for the module. And in this command:

browserify --exclude level.js main.js > bundle-main.js

you are telling Browserify that when it sees require('level.js') it should not bundle anything, because the require will be resolved at runtime with a between-bundle require .

You should use a non-relative name in the require (and, if its a normal JavaScript file, leave off the .js , too):

browserify --require ./level.js:level > bundle-level.js
browserify --exclude level main.js > bundle-main.js

Then the require in main.js should be:

const level = require('level');

If you want to export num3 and num4 , you can do so in level.js like this:

exports.num3 = require('./num3');
exports.num4 = require('./num4');

And in main.js you would then have:

const level = require('level');
console.log(level.num3);
console.log(level.num4);

If you are interested in Node's module resolution mechanism (which Browserify emulates), it's described here . The --require and --exclude Browserify options basically subvert that mechanism and instruct Browserify to resolve between bundles at runtime instead.

Also, if you want, you can specify multiple modules for require -ing between bundles:

browserify \
  --require ./num3.js:num3 \
  --require ./num4.js:num4 \
  --require ./level.js:level > bundle-level.js
browserify \
  --exclude num3 \
  --exclude num4 \
  --exclude level main.js > bundle-main.js

And in main.js :

const level = require('level');
const num3 = require('num3');
const num4 = require('num4');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM