Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bundle isomorphic commonJS code with webpack

I have a project that uses nodeJS module format (commonJS) and should also (in parts) run in the browser.

I do have non-isomorphic code paths where I conditionally include modules:

var impl;
try {
    // in node, use node-impl
   impl = require('../node-impl');
} catch (err) {
    // running in browser, use browser-impl
    impl = require('../browser-impl');
}

Now, I want to use webpack to create a bundle that runs in the browser. I therefore need to defined the external (nodeJS specific) modules as external in the webpack.config.js so that they don't get included in the bundle:

external: {
    '../node-impl': true
}

I verified that the '../node-impl' code is actually not included in bundle, but the emitted code looks like this:

/***/ },
/* 33 */
/***/ function(module, exports) {

    module.exports = ../node-impl;

/***/ },

This is syntactically wrong JS and the browser will throw a syntax error there.

How is this scenario properly handled with webpack.js? Be aware that I do not wish to use webpack for running with nodeJS, only the browser bundles should be created with webpack.

like image 991
Dynalon Avatar asked Jun 04 '26 21:06

Dynalon


1 Answers

// Your actual situation: var impl; try { impl = require('../node-impl'); } catch(e) { impl = require('../browser-impl'); }

You need to refactor this snippet to:

var impl = require('../node-impl');

After this rework, your code is able to work only in a node js environment, that's is good because we are going to mock this request when bundling for browsers... // webpack.browser.config.js module.exports = { resolve: { alias: { '../node-impl': '../browser-impl' } } };

Webpack - Resolve.Alias Or using a package.json#browser, or https://webpack.github.io/docs/configuration.html#resolve-packagealias

like image 184
Hitmands Avatar answered Jun 06 '26 09:06

Hitmands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!