Webpack Conditional Require

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!

2

2 Answers

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.

1

webpack.config.js

module.exports = {
plugins: [
    new webpack.DefinePlugin({
        "process.env": {
            BROWSER: JSON.stringify(true)
        }
    })
]}

your-universal.js

var db = null;
if (!process.env.BROWSER) {
    // node context
    db = require('level');
} else {
    // browser context
    db = require('gazel');
}
8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest