Webpack conditional require

vardump picture vardump · Jul 6, 2015 · Viewed 15.5k times · Source

I'm writing an isomorphic Key Value Store with webpack.

This is currently my approach to load the libraries, which obviously doesn't work, because webpack wants to resolve both require. Whats' the right approach?

var db = null;

if (typeof window === 'undefined') {
    // node context
    db = require('level');
} else {
    // browser context
    db = require('gazel');
}

I know, that you can provide a target to webpack. But I have no idea how to use that.

Thanks!

Answer

Juho Vepsäläinen picture Juho Vepsäläinen · Jul 6, 2015

I think resolve.alias would work for you. You would set db module to point at level or gazel depending on which build you are creating.