0

I've written a plug-in for Webpack that takes my generated React component, renders it in Node, and then inserts it into the generated HTML document.

This used to work fine in Webpack 3. To upgrade it to Webpack 4, I replaced

compiler.plugin("after-emit", compilation => {

with

compiler.hooks.afterEmit.tap('prerender-plugin', (compilation) => {

which, as far as I can see, should be sufficient.

In the plug-in, I ask Webpack for the path to my generated bundle and then require that, roughly as follows:

    const assetHash = Object.keys(compilation.assets).filter(asset => /app(.*).js/.test(asset))[0];
    const appFilePath = compilation.assets[assetHash].existsAt;
    // The `.default` is needed because it's an ES2015 module
    const App = require(appFilePath).default;

However, I then all of a sudden hit errors like the following as a result of the require:

ReferenceError: window is not defined
    at Object.<anonymous> (/home/vincent/Workspace/Flockademic/stacks/frontend/dist/app.da5512cf55a3c4446086.js:1:286)
...

The offending code seems to be some standard Webpack top matter:

!function(e,i){if("object"==typeof exports&&"object"==typeof module)module.exports=i();else if("function"==typeof define&&define.amd)define([],i);else{var a=i();for(var o in a)("object"==typeof exports?exports:e)[o]=a[o]}}(window,function(){return function(e){var i={};function a(o){if

(Note that this sample is up to the supposedly-offending column. As you can see, window is not actually referred to on column 286.)

I'm not that familiar with Webpack, and documentation on plug-ins relatively scarce, so any pointers on how to get closer to solving this are very much welcome/

Vincent
  • 4,876
  • 3
  • 44
  • 55

1 Answers1

-1

Add this at your root .js file will probably work.

if (typeof window === 'undefined') { global.window = {}; }

iik
  • 73
  • 1
  • 9