Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute webpack compiled bundle in NodeJS

I want to implement server-side rendering for my ReactJS app. I use react-router. I take routes.js as webpack entry point and compile with output.libraryTarget = "commonjs2" option. Then I require the result of compilation in NodeJS script to make rendering. But I've got en error. Webpack wrap modules in following code:

/* 277 */
/***/ function(module, exports, __webpack_require__) {

    /* WEBPACK VAR INJECTION */(function(Buffer, global) {
    if (global.foo) {
        /* ... */
    }
    /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(277).Buffer, (function() { return this; }())))

 /***/ }

When NodeJS tries to execute (function() { return this; }()) its return undefined. In browser it will return window. Why webpack use such wrap code? How to make this code works in NodeJS?

I use node-clone as external lib. It don't use any other libs as dependency. But webpack in its bundle makes buffer as a dependency for this lib. And inside the buffer code I've got en error Cannot read property 'TYPED_ARRAY_SUPPORT' of undefined. It happens because in nodeJS (function() { return this; }()) return undefined.

like image 596
Anton Rodin Avatar asked Jun 08 '26 18:06

Anton Rodin


1 Answers

By default, webpack will package things up for browsers. If you want to build Node libraries with webpack, you need to specifiy a target in your configuration:

module.exports = {
  // ...

  target: 'node',
};
like image 197
Josh David Miller Avatar answered Jun 10 '26 08:06

Josh David Miller