【问题标题】:How do I use jsdom with Gatsby (aka use webpack target node)?如何将 jsdom 与 Gatsby 一起使用(又名使用 webpack 目标节点)?
【发布时间】:2021-03-30 04:51:41
【问题描述】:

我想在 Gatsby 项目中使用 jsdom,以便能够在 React 组件中加载和呈现单独的网页。

但是,当我尝试使用 Gatsby 构建时,我收到了一系列 Webpack 错误,如下所示:

未定义失败

无法解析“child_process” '/Users/john/WebstormProjects/analytics/web/node_modules/jsdom/lib/jsdom/living/xhr'

我认为这可能是因为 Webpack 使用的是 'web' 目标模式而不是 'node'。我尝试将webpack.config.js 文件放在根目录中:

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

但是,这并没有做任何事情。我也尝试使用onCreateWebpackConfig,但我不确定这是否正确,因为我也无法让它工作:

//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',
  });
}

我有两个问题:

  1. 是否可以在 Gatsby 项目中使用jsdom,如果可以,我需要做什么?如果只是使用target模式,那么:

  2. 如何将 Gatsby 中的 target 模式设置为 node 而不是 web

【问题讨论】:

    标签: javascript node.js webpack gatsby jsdom


    【解决方案1】:
    1. 如何将 Gatsby 中的目标模式设置为节点而非 Web?

    看起来你可以改变 webpack 配置来设置目标:

    // gatsby-node.js
    exports.onCreateWebpackConfig = ({ actions, getConfig }) => {
      const config = getConfig();
      config.target = 'node';
      actions.replaceWebpackConfig(config);
    };
    

    https://www.gatsbyjs.com/docs/how-to/custom-configuration/add-custom-webpack-config/#modifying-the-babel-loader

    【讨论】:

      猜你喜欢
      • 2015-02-18
      • 2020-12-11
      • 2015-09-15
      • 2016-11-23
      • 1970-01-01
      • 2018-10-20
      • 2015-11-30
      • 2018-10-24
      • 1970-01-01
      相关资源
      最近更新 更多