How do I use jsdom with Gatsby (aka use webpack target node)?

Viewed 397

I want to use jsdom within a Gatsby project, in order to be able to load and render a separate webpage within a React component.

However, when I try to build with Gatsby, I get a series of Webpack errors which look like this:

undefined failed

Can't resolve 'child_process' in '/Users/john/WebstormProjects/analytics/web/node_modules/jsdom/lib/jsdom/living/xhr'

I think this may be because Webpack is using the 'web' target mode and not 'node'. I've tried putting a webpack.config.js file in the root directory:

module.exports = {
  target: 'node',
}

However, this didn't do anything. I also tried to use onCreateWebpackConfig, but I'm not sure if this is correct, as I couldn't get this to work either:

//gatsby-node.ts
export { onCreateWebpackConfig } from "./src/gatsby/on-create-webpack-config";


// ./src/gatsby/on-create-webpack-config
export const onCreateWebpackConfig = ({ actions } : any) => {
  actions.setWebpackConfig({
    target: 'node',
  });
}

I have 2 questions:

  1. Is it possible to use jsdom in a Gatsby project and if so, what do I need to do? If it's just to use the target mode, then:

  2. How do I set the target mode in Gatsby to be node and not web?

1 Answers
Related