Why would webpack output with global `self` instead of `this` when output.globalObject: "this" is specified?

2.4k Views Asked by At

I am using webpack-cli 4.7.0. I have a library that I would like to compile for two different environments, one for web and one for node. According to this documentation this is easily achieved my exporting two separate, valid webpack configurations from webpack.config.js.

So I have created two valid webpack configs, one for server and one for client. Webpack outputs two separate files as specified, but insists on using "self" instead of "this" even though I have output.globalObject: "this" specified in the configuration. If I am understanding the official documentation, such should not be the case.

webpack.config.js

const path = require( "path" );
// const webpack = require( "webpack" );


const serverConfig  = {
    mode: "production",
    entry: "./src/Check4.js",
    target: "node",
    output: {
        path: path.resolve( __dirname, "dist" ),
        filename: "Check4.node.js",
        globalObject: "this",
        library : {
            type: "commonjs2",
            export: "default"

        }

    }
};

const clientConfig  = {
    mode: "production",
    entry: "./src/Check4.web.js",
    target: "web",
    output: {
        path: path.resolve( __dirname, "dist" ),
        filename: "Check4.js",
        globalObject: "this",
        library : {
            name: "Check4",
            type: "window",
        }
    }
};

module.exports = [serverConfig, clientConfig];

for reference, here are the first several bytes output by webpack to show that it is using global "self" instead of "this"

(()=>{var e={172:e=>{self,e.exports=(()=>{"use strict";var e={502:...
1

There are 1 best solutions below

0
On BEST ANSWER

The answer was in my dependencies. I had written a class which this class depended upon. The parent class was not compiled, so webpack was trying to compile both at the same time.

After many hours I stumpbled upon this which led me to solving the issue. https://github.com/markdalgleish/static-site-generator-webpack-plugin/issues/79

Hey, update; After looking around a tad, it looks like for me, this error is coming from isomorphic-fetch dependency (https://github.com/matthew-andrews/iso…). Seems similar to document is not defined kind of issues people get, since this pre rendering doesn't happen in a browser context. I don't have any more time to look at it today for why that's the case or for solutions, but that's my hunch. Check your polyfills and dependencies.