hughsk / envify

:wrench: Selectively replace Node-style environment variables with plain strings.
902 stars 57 forks source link

Could envify be used to enable dynamic-ish require() statements with browserify? #41

Open JedWatson opened 8 years ago

JedWatson commented 8 years ago

Just following a thread here, not sure if it's possible or not.

As noted in substack/node-browserify#377 browserify uses static analysis to figure out what to build.

I'm working on a network of sites where we want to include different config for each property, where the property is identified by an environment variable.

That means we have a config file that looks like this:

if (process.env.SITE_KEY === 'site1') {
    module.exports = require('./site1');
} else if (process.env.SITE_KEY === 'site2') {
    module.exports = require('./site2');
}

Any other module that wants to know something in the site config requires this one.

The problem is that all site configs are bundled into each site's build, even though only the active one is used. Not really a huge issue, but it's not a clean solution either.

It seems like it might be possible to hook envify into the browserify pipeline in a way that replaces environment variables before require statements are evaluated, which would allow the following:

module.exports = require('./' + process.env.SITE_KEY);

If we could rewrite that with envify before browserify goes looking for require statements, it would see:

module.exports = require('./site1');

Any ideas on whether that's possible / feasible? Or do you know of any other ways to achieve this? I went looking but didn't find anything.

hughsk commented 8 years ago

@JedWatson envify does indeed get applied before browserify looks for require statements! I think it should work using require('./' + process.env.SITE_KEY) but gotta try and see :)

SteffanDonal commented 8 years ago

Weighing in my two pennies here - I can confirm that this does not work.

You must specifically require individual modules using a constant string.

ewnd9 commented 7 years ago

--exclude from browserify itself should work, something like

$ browserify index.js --exclude 'src/site2.js' -g [ envify purge --SITE_KEY=site1  ]