此页面需要javascript支持,请在浏览器中启用javascript

Nuxt Generate 遇到一个问题

nuxt
Generate
static
共337个字,阅读时间 2 分钟
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://icebreaker.top/articles/2020/10/nuxt-generate-1

The command 'nuxt generate' finished but did not exit after 5s
This is most likely not caused by a bug in Nuxt.js
Make sure to cleanup all timers and listeners you or your plugins/modules start.
Nuxt.js will now force exit
DeprecationWarning: Starting with Nuxt version 3 this will be a fatal error
相关的 issues

The issues comes because we actually import the serverMiddleware when running nuxt build. 也就是说作者推荐我们写一个 module来动态添加 serverMiddleware

module.exports = function (moduleOptions) {
  // Add middleware only with `nuxt dev` or `nuxt start`
  if (this.options.dev || this.options._start) {
    this.addServerMiddleware('xxx')
  }
}

更换为本项目时,直接

import serverMiddlewares from '~/serverMiddleware/index'

却出现了找不到 ~/serverMiddleware/index 的问题,原因在于 module 的加载是先于 nuxt 的 alias 分析的,那么问题来了 本人不喜欢使用 commonjs + 非常想用 alias , 此时自然而然想到了 rollup

我把 serverMiddleware的入口从

export default [
  {
    path: '',
    handler: '@/serverMiddleware/sitemap/index.js',
  },
  {
    path: '/api',
    handler: '@/serverMiddleware/router/index.js',
  },
  {
    path: '/graphql',
    handler: '@/serverMiddleware/dist/graphql/index.js',
  },
]

to

import sitemap from '~/serverMiddleware/sitemap/index.js'
import api from '~/serverMiddleware/router/index.js'
import graphql from '~/serverMiddleware/graphql/index.js'
export default [
  {
    path: '',
    handler: sitemap,
  },
  {
    path: '/api',
    handler: api,
  },
  {
    path: '/graphql',
    handler: graphql,
  },
]

把 nuxt 的解析交给了 rollup 做

然后在 ~/modules/loadServerMiddleware/index 引入

import serverMiddlewares from '~/serverMiddleware/index.js'

export default function loadServerMiddleware(moduleOptions) {
  // Add middleware only with `nuxt dev` or `nuxt start`
  if (this.options.dev || this.options._start) {
    serverMiddlewares.forEach((x) => {
      this.addServerMiddleware(x)
    })
  }
}

这样就完成了只在 nuxt dev 或者 nuxt start 的时候添加 serverMiddleware