【问题标题】:process.server is undefined in Nuxt.js modules在 Nuxt.js 模块中未定义 process.server
【发布时间】:2020-01-28 11:53:04
【问题描述】:

我正在使用 Nuxt.js 模块,如果 process.server 为 true,该模块会添加一个插件,但它不起作用。我尝试使用 typescript 模块记录 process.server

export default function (moduleOptions?: any) {
  console.log(process.server);
};

它显示:

yarn run v1.17.3
$ nuxt-ts
undefined                                                             22:00:16

   ╭──────────────────────────────────────────╮
   │                                          │
   │   Nuxt.js v2.9.2                         │
   │   Running in development mode (spa)      │
   │                                          │
   │   Listening on: http://localhost:3000/   │
   │                                          │
   ╰──────────────────────────────────────────╯

我该如何解决?

【问题讨论】:

    标签: javascript node.js typescript nuxt.js


    【解决方案1】:

    来自docs

    模块只是在启动 Nuxt 时顺序调用的函数。

    换句话说,模块总是从服务器调用,并在设置 Nuxt 实例时调用。由于这个原因,process.server 是未定义的,因为 Nuxt 还没有定义它。

    您可以改用name conventional plugins,它在文件名中使用clientserver 后缀来确定它们应该在哪里运行。下面的例子展示了如何使用这个从模块中添加插件:

    import path from 'path'
    
    export default function (moduleOptions) {
      // Register your plugin here with .server in the name
      // to only run on the server.  This expects the plugin file to 
      // be located next to this module file
      this.addPlugin(path.resolve(__dirname, 'plugin.server.ts'))
    }
    

    【讨论】:

    • 我认为它有效(发生错误),但我找不到有关名称约定的文档
    猜你喜欢
    • 1970-01-01
    • 2021-01-15
    • 2019-02-20
    • 2018-02-13
    • 2019-07-25
    • 2015-09-09
    • 1970-01-01
    • 2021-07-22
    • 2021-01-13
    相关资源
    最近更新 更多