Skip to content
Advertisement

How to make webpack not use the window object when bundling?

I’m making a React component library to abstract out some components I use in multiple projects. Some projects are made with CRA, some with Gatsby, some might be something else, etc. I used the Neutrino.js framework/toolchain as it was linked on the React docs site, but the issue I ran into is that by default the output files of the build all use the window object, which causes gatsby build to break as window doesn’t exist in Node/SSR. Is there a way to make Neutrino/webpack output a bundle that doesn’t use window? While searching for a solution and comparing to other libraries it seems that ESM is the best but I’m not sure how to get webpack to use it, I think it’s currently not supported. Is there another tool I should be using for this?

Advertisement

Answer

Add globalObject configuration to your webpack configuration:

output: {
    globalObject: "this",
  },

The default is window

For example:

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

module.exports = {
  // ...
  output: {
    library: 'myLib',
    libraryTarget: 'umd',
    filename: 'myLib.js',
    globalObject: 'this'
  }
};

-From docs

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement