API: The hooks Property

hooks 属性

例如 (nuxt.config.js):

  1. import fs from 'fs'
  2. import path from 'path'
  3. export default {
  4. hooks: {
  5. build: {
  6. done(builder) {
  7. const extraFilePath = path.join(
  8. builder.nuxt.options.buildDir,
  9. 'extra-file'
  10. )
  11. fs.writeFileSync(extraFilePath, 'Something extra')
  12. }
  13. }
  14. }
  15. }

在内部,hooks 遵循使用冒号的命名模式(例如,build:done)。为了便于配置,当使用nuxt.config.js(如上所示)设置自己的钩子时,可以将它们构造为分层对象。有关它们如何工作的更多详细信息,请参考Nuxt Internals

hooks 列表

例子

不在 root 上时重定向到 router.base

Let´s say you want to serve pages as /portal instead of /. 假设您希望将页面作为 /portal 而不是 / 来提供。这可能是一个边缘情况, nuxt.config.jsrouter.base用于当 Web 服务器,服务 Nuxt 而不是域根目录时。

但是当在本地开发时,遇到 localhost,当 router.base 不是 / 返回 404 时。为了防止这种情况,你可以设置一个 Hook。

也许重定向不是生产网站的最佳用例,但这将有助于您利用 Hooks。

首先,你可以 改变 router.base;更新你的 nuxt.config.js:

  1. // nuxt.config.js
  2. import hooks from './hooks'
  3. export default {
  4. router: {
  5. base: '/portal'
  6. }
  7. hooks: hooks(this)
  8. }

然后,创建一些文件;

  1. hooks/index.js, Hooks 模块

    1. // file: hooks/index.js
    2. import render from './render'
    3. export default nuxtConfig => ({
    4. render: render(nuxtConfig)
    5. })
  2. hooks/render.js, 渲染 hook

    1. // file: hooks/render.js
    2. import redirectRootToPortal from './route-redirect-portal'
    3. export default nuxtConfig => {
    4. const router = Reflect.has(nuxtConfig, 'router') ? nuxtConfig.router : {}
    5. const base = Reflect.has(router, 'base') ? router.base : '/portal'
    6. return {
    7. /**
    8. * 'render:setupMiddleware'
    9. * {@link node_modules/nuxt/lib/core/renderer.js}
    10. */
    11. setupMiddleware(app) {
    12. app.use('/', redirectRootToPortal(base))
    13. }
    14. }
    15. }
  3. hooks/route-redirect-portal.js, 中间件本身

    1. // file: hooks/route-redirect-portal.js
    2. /**
    3. * Nuxt middleware hook to redirect from / to /portal (or whatever we set in nuxt.config.js router.base)
    4. *
    5. * Should be the same version as connect
    6. * {@link node_modules/connect/package.json}
    7. */
    8. import parseurl from 'parseurl'
    9. /**
    10. * Connect middleware to handle redirecting to desired Web Applicatin Context Root.
    11. *
    12. * Notice that Nuxt docs lacks explaning how to use hooks.
    13. * This is a sample router to help explain.
    14. *
    15. * See nice implementation for inspiration:
    16. * - https://github.com/nuxt/nuxt.js/blob/dev/examples/with-cookies/plugins/cookies.js
    17. * - https://github.com/yyx990803/launch-editor/blob/master/packages/launch-editor-middleware/index.js
    18. *
    19. * [http_class_http_clientrequest]: https://nodejs.org/api/http.html#http_class_http_clientrequest
    20. * [http_class_http_serverresponse]: https://nodejs.org/api/http.html#http_class_http_serverresponse
    21. *
    22. * @param {http.ClientRequest} req Node.js internal client request object [http_class_http_clientrequest]
    23. * @param {http.ServerResponse} res Node.js internal response [http_class_http_serverresponse]
    24. * @param {Function} next middleware callback
    25. */
    26. export default desiredContextRoot =>
    27. function projectHooksRouteRedirectPortal(req, res, next) {
    28. const desiredContextRootRegExp = new RegExp(`^${desiredContextRoot}`)
    29. const _parsedUrl = Reflect.has(req, '_parsedUrl') ? req._parsedUrl : null
    30. const url = _parsedUrl !== null ? _parsedUrl : parseurl(req)
    31. const startsWithDesired = desiredContextRootRegExp.test(url.pathname)
    32. const isNotProperContextRoot = desiredContextRoot !== url.pathname
    33. if (isNotProperContextRoot && startsWithDesired === false) {
    34. const pathname = url.pathname === null ? '' : url.pathname
    35. const search = url.search === null ? '' : url.search
    36. const Location = desiredContextRoot + pathname + search
    37. res.writeHead(302, {
    38. Location
    39. })
    40. res.end()
    41. }
    42. next()
    43. }

然后,每当开发中的同事到达开发 Web 开发服务/时,发生了意外情况,Nuxt 将自动重定向到/portal