How to configure globobject in webpack correctly?

I wrote an NPM package by myself, and configured the libraryTarget configuration in the Webpack to generate js files in umd mode, so that packages can be imported in both NPM mode and script tag mode.

However, when the package is imported into the SSR rendered application, an error occurs.

The Error ” window is not defined

When I configure globobject in webpack occurs Error ” window is not defined”. The prompt window is not defined is prompted after I direct import package.

Why? Why it prompts ” window is not defined”?

Because in the application of the SSR, the server executes the Global Code ahead of time, and the creation of the dom and the previous lifecycle of the component is executed, but there is no top-level window object in node, so the error is reported.

I thought it was because of the direct call to window in the code, and then I did the if detection, but it was still with the error.

After I looked at the code in development mode, I found that one of the parameters passed in was actually a window object

How to Configure Globobject  in Webpack?

So. I come to in contrast to the UMD written specification find that the parameter should be passed to this, which points to the current environment.

UMD written specification

How to deal with the error of configure globobject in webpack ?

Firstly, I see the globalObject configuration in the webpack documentation:

To make UMD build available on both browsers and Node.js, set output.globalObject option to ‘this’.

As we have known, since it defaults to window, we need to change it to this, modify the output configuration in the Webpack, and add the globalObject configuration:

//....
output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    libraryExport: 'default',
    library: '[name]',
    globalObject: 'this',   // here
    libraryTarget: 'umd'
}
//....

Attention to configure globobject in webpack:

  • NPM also has internal window or document only under the browser to use the object, but still with the error. Which can be done inside the code if decision processing.
  • Without the if processing, the API in the NPM package is used only in the corresponding lifecycle to avoid errors.

By that way, now the packaged files can be imported directly into the SSR project. It works very well.