应该如何用NuxtJS配置jsdom?

时间:2019-03-02 19:21:17

标签: jquery node.js jsdom

我正在尝试在NuxtJS上使用jQuery。遵循reserved keywords之后,很明显我得到了错误,指出jQuery需要窗口上下文。我安装了jsdom及其所有依赖项,并使用了this tutorial,但是每次运行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

1 个答案:

答案 0 :(得分: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

相关问题