在 nuxt 中使用 newrelic

Use newrelic in nuxt

我正在尝试将 newrelic 代理添加到我的 nuxt 应用程序中。我已经安装了所需的软件包并添加了我的许可证密钥并在 newrelic.js 配置文件中设置了一个应用程序名称:

npm i newrelic
cp node_modules/newrelic/newrelic.js .
nano newrelic.js

我的问题是我还需要在我的 server.js 文件的顶部要求这个配置文件,因为这个文件是动态创建的并放在 .nuxt 文件夹下我不知道如何这样做。

在标准的 nodejs 应用程序中,我只需将 require('newrelic'); 添加到启动脚本的顶部,或者在 package.json 中添加一个新的脚本条目,如下所示:

"scripts": {
  "dev": "node -r newrelic.js app.js"
}

我最终使用 express 来解决这个问题:

npm i express
touch server/index.js

我们现在将在 server/index.js 文件中加载 newrelic,然后创建我们的 nuxt 实例:

require('newrelic');
const express = require('express');
const consola = require('consola');
const { Nuxt, Builder } = require('nuxt');
const app = express();

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js');
config.dev = process.env.NODE_ENV !== 'production';

async function start () {
  // Init Nuxt.js
  const nuxt = new Nuxt(config);

  const { host, port } = nuxt.options.server;

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt);
    await builder.build();
  } else {
    await nuxt.ready();
  }

  // Give nuxt middleware to express
  app.use(nuxt.render);

  // Listen the server
  app.listen(port, host);
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  });
}
start();

我还更新了 package.json 中的 script 部分:

"scripts": {
  "dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
  "build": "nuxt build",
  "start": "cross-env NODE_ENV=production node server/index.js"
}

希望对遇到同样问题的人有所帮助。

对于任何为此苦苦挣扎的人,我通过使用 Nuxt modules and hooks.

找到了一个更简单的解决方案

创建一个包含以下内容的新文件modules/newRelic.js

module.exports = function () {
  this.nuxt.hook("listen", () => {
    require("newrelic");
  });
};

导入nuxt.config.js

中的模块
modules: [
  "~/modules/newRelic.js"
]

不要忘记安装 newrelic (npm i newrelic) 并将 newrelic.js 粘贴到应用程序根文件夹中。