spatie / server-side-rendering

Server side rendering JavaScript in a PHP application
https://sebastiandedeyne.com/posts/2018/server-side-rendering-javascript-from-php
MIT License
602 stars 34 forks source link

fix process object override #49

Closed Kal-Aster closed 3 years ago

Kal-Aster commented 3 years ago

This PR solves #48

sebastiandedeyne commented 3 years ago

Why is this change neceesary? I don't see any reasoning in the initial bug report.

Kal-Aster commented 3 years ago

Sorry for not providing enough information.

It is needed because declaring process via var ovverrides any already existing process variable. So having var process = process || { env: {} } will result always in { env: {} } because process points to itself, initialized to undefined, and not to the global process, if any.

I'll explain my code:

// the following function is called with null, so `this` will be the global object
// it would be better to do `(1, eval)("this")` but because it's in the beginning of the file, I think `null` is enough
(function () {
  // if the global object already has `process` then do nothing
  if (this.process != null) {
    return;
  }
  // if the global object has not `process` yet, create it with default values
  // here, I added also argv and now I think that this could be populated with the node path as first item
  this.process = { env: {}, argv: [] };
}).call(null)