node.js - 以编程方式使用 Nuxt,无需构建器

标签 node.js express nuxt.js

我在express中以编程方式使用nuxt和nuxt.render中间件,如下所示

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

const api = require('../api')
app.use('/api', api)

let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

// Init Nuxt.js
const nuxt = new Nuxt(config)
app.use(nuxt.render)

async function start() {
// Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  // Listen the server
  app.listen(port, host)
  console.log('Server listening on ' + host + ':' + port)
}
start()

当我开发服务器 api 路由并对服务器端 api 文件进行一些更改并重新启动服务器时,每次都会构建整个 nuxt 项目,这花费了太多时间。这很不方便,因为 nuxt 文件没有变化,只有 api 路由文件变化。

因此,构建一次后,我注释掉以下几行:

if (config.dev) {
// const builder = new Builder(nuxt)
// await builder.build()
}

然后我重新启动服务器,这当然不会启动 nuxt 构建器。但是我现在无法在浏览器上访问 nuxt 。服务器 api 路由有效,但 nuxt 页面路由仅显示“Nuxt 加载…”屏幕。

如何在开发模式下使用 nuxt 应用程序而不需要每次都构建它?

最佳答案

这可能是一个有效的用例,有时人们不想为非常小的 api/ui 对使用两台服务器。我还建议采用一种通过 nuxt/proxy 工作的分离模式,并且您可以在进行开发工作时运行它。在分离模式下,你的 nuxt 单独工作,api 也单独运行,并且 nuxt 通过 `nuxt/proxy 模仿上述设置。通过在 nuxt 配置中添加这样的东西来设置非常容易

  modules: [
    ['@nuxtjs/proxy', {    "/api/": { target: 'http://localhost:888/api'} }]
  ]

在产品中你可以像以前一样运行。

关于node.js - 以编程方式使用 Nuxt,无需构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56394061/

相关文章:

node.js - 无法使用 mongoose 和 nodejs 访问对象值

javascript - Expressjs路由映射

Nuxt.js vuex 存储未持久化

error-handling - Nuxt 处理来自 Prismic API 的获取错误

node.js - 使用 sails.js 时如何安全地存储连接字符串

javascript - 查找所有以特定字符开头的单词,后跟字符串中的数字

express - 客户端收到所有 .ts 文件后自动删除 .ts 和 .m3u8 文件

node.js - 使用 Controller 内的 Express 和 Multer 解析请求

javascript - 图像未上传到nodejs中的数据库

nuxt.js - 在nuxt中使用自定义布局更改页面时如何修复 `Invalid component name`?