【问题标题】:How should jsdom be configured with NuxtJS?jsdom应该如何配置NuxtJS?
【发布时间】:2019-07-24 12:30:24
【问题描述】:

我正在尝试在 NuxtJS 上使用 jQuery。在关注this tutorial 之后,我显然收到错误消息说 jQuery 需要一个窗口上下文。我安装了 jsdom 及其所有依赖项并使用它as it should be,但每次我运行npm run dev 时总是弹出以下错误:

 ERROR  Failed to compile with 5 errors                                                      friendly-errors 14:13:40

These dependencies were not found:                                                           friendly-errors 14:13:40
                                                                                             friendly-errors 14:13:40
* child_process in ./node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js                   friendly-errors 14:13:40
* fs in ./node_modules/jsdom/lib/jsdom/browser/resources/resource-loader.js, ./node_modules/jsdom/lib/jsdom/living/xhr-utils.js and 2 others
                                                                                             friendly-errors 14:13:40
To install them, you can run: npm install --save child_process fs

请注意,这些依赖项确实已安装并且是最新的。这是由于 Nuxt 双方的冲突吗?如何完全解决或以其他方式解决?

我还设置了一个插件,通过 jsdom 始终拥有默认的窗口上下文:

jsdom.js

var jsdom = require("jsdom")
const { JSDOM } = jsdom

const { document } = new JSDOM("").window
global.document = document

【问题讨论】:

    标签: jquery node.js jsdom


    【解决方案1】:

    要使用 jsdom,你必须修改 nuxt.configure.js。修改nuxt.configure.js后,重启nuxt。

    export default {
      // some configurations
      build: {
        /*
        ** You can extend webpack config here
        */
        extend (config, { isDev, isClient }) {
          if (isClient) {
            config.node = {
              fs: 'empty',
              child_process: 'empty',
            }
          }
        }
      },
      // other configurations
    }
    

    如果您遇到相同的依赖错误,只需在 config.node 中添加相同的设置,如下所示。

              fs: 'empty',
              child_process: 'empty',
              tls: 'empty',
              net: 'empty',
    

    在这种情况下,我认为您实际上不需要在代码中使用 fs、child_process,但它们会阻止您导入 jsdom。 通过上述配置,您可以将 fs 和 child_proccess 替换为空对象,并抑制构建错误。因此,如果您尝试使用依赖于这些库的函数,例如使用文件方案获取,它将失败。

    关于 config.node 的详细信息记录在这里:https://webpack.js.org/configuration/node/#other-node-core-libraries

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 2021-10-05
      • 2020-03-23
      • 2021-07-29
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      相关资源
      最近更新 更多