NuxtJS应该如何配置jsdom?

T14*_*145 3 jquery node.js jsdom

我正在尝试在 NuxtJS 上使用 jQuery。遵循本教程后,我显然收到错误消息,指出 jQuery 需要窗口上下文。我安装了 jsdom 及其所有依赖项并按原样使用它,但每次运行时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
Run Code Online (Sandbox Code Playgroud)

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

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

jsdom.js

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

const { document } = new JSDOM("").window
global.document = document
Run Code Online (Sandbox Code Playgroud)

小智 5

要使用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
}
Run Code Online (Sandbox Code Playgroud)

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

          fs: 'empty',
          child_process: 'empty',
          tls: 'empty',
          net: 'empty',
Run Code Online (Sandbox Code Playgroud)

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

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