Nuxt.js hooks 屬性

2022-03-03 15:44 更新

hooks 屬性

例如 (nuxt.config.js):

import fs from 'fs'
import path from 'path'

export default {
  hooks: {
    build: {
      done (builder) {
        const extraFilePath = path.join(builder.nuxt.options.buildDir, 'extra-file')
        fs.writeFileSync(extraFilePath, 'Something extra')
      }
    }
  }
}

在內(nèi)部,hooks遵循使用冒號(hào)的命名模式(例如,build:done)。為了便于配置,當(dāng)使用nuxt.config.js(如上所示)設(shè)置自己的鉤子時(shí),可以將它們構(gòu)造為分層對(duì)象。有關(guān)它們?nèi)绾喂ぷ鞯母嘣敿?xì)信息,請(qǐng)參考Nuxt Internals

hooks 列表

例子

不在root上時(shí)重定向到 router.base

Let′s say you want to serve pages as /portal instead of /. 假設(shè)您希望將頁(yè)面作為 /portal 而不是 / 來(lái)提供。 這可能是一個(gè)邊緣情況, _nuxt.config.js_’ router.base用于當(dāng)Web服務(wù)器,服務(wù)Nuxt而不是域根目錄時(shí)。

但是當(dāng)在本地開(kāi)發(fā)時(shí),遇到 _localhost_,當(dāng)router.base不是 / 返回404時(shí)。為了防止這種情況,你可以設(shè)置一個(gè)Hook。

也許重定向不是生產(chǎn)網(wǎng)站的最佳用例,但這將有助于您利用Hooks。

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

// nuxt.config.js
import hooks from './hooks'
export default {
  router: {
    base: '/portal'
  }
  hooks: hooks(this)
}

然后,創(chuàng)建一些文件;

  1. hooks/index.js, Hooks 模塊
// file: hooks/index.js
import render from './render'

export default nuxtConfig => ({
  render: render(nuxtConfig)
})


2. hooks/render.js, 渲染 hook

// file: hooks/render.js
import redirectRootToPortal from './route-redirect-portal'

export default (nuxtConfig) => {
  const router = Reflect.has(nuxtConfig, 'router') ? nuxtConfig.router : {}
  const base = Reflect.has(router, 'base') ? router.base : '/portal'

  return {
    /**
     * 'render:setupMiddleware'
     * {@link node_modules/nuxt/lib/core/renderer.js}
     */
    setupMiddleware (app) {
      app.use('/', redirectRootToPortal(base))
    }
  }
}


3. hooks/route-redirect-portal.js, 中間件本身

// file: hooks/route-redirect-portal.js

/**
 * Nuxt middleware hook to redirect from / to /portal (or whatever we set in nuxt.config.js router.base)
 *
 * Should be the same version as connect
 * {@link node_modules/connect/package.json}
 */
import parseurl from 'parseurl'

/**
 * Connect middleware to handle redirecting to desired Web Applicatin Context Root.
 *
 * Notice that Nuxt docs lacks explaning how to use hooks.
 * This is a sample router to help explain.
 *
 * See nice implementation for inspiration:
 * - https://github.com/nuxt/nuxt.js/blob/dev/examples/with-cookies/plugins/cookies.js
 * - https://github.com/yyx990803/launch-editor/blob/master/packages/launch-editor-middleware/index.js
 *
 * [http_class_http_clientrequest]: https://nodejs.org/api/http.html#http_class_http_clientrequest
 * [http_class_http_serverresponse]: https://nodejs.org/api/http.html#http_class_http_serverresponse
 *
 * @param {http.ClientRequest} req Node.js internal client request object [http_class_http_clientrequest]
 * @param {http.ServerResponse} res Node.js internal response [http_class_http_serverresponse]
 * @param {Function} next middleware callback
 */
export default desiredContextRoot =>
  function projectHooksRouteRedirectPortal (req, res, next) {
    const desiredContextRootRegExp = new RegExp(`^${desiredContextRoot}`)
    const _parsedUrl = Reflect.has(req, '_parsedUrl') ? req._parsedUrl : null
    const url = _parsedUrl !== null ? _parsedUrl : parseurl(req)
    const startsWithDesired = desiredContextRootRegExp.test(url.pathname)
    const isNotProperContextRoot = desiredContextRoot !== url.pathname
    if (isNotProperContextRoot && startsWithDesired === false) {
      const pathname = url.pathname === null ? '' : url.pathname
      const search = url.search === null ? '' : url.search
      const Location = desiredContextRoot + pathname + search
      res.writeHead(302, {
        Location
      })
      res.end()
    }
    next()
  }


然后,每當(dāng)開(kāi)發(fā)中的同事到達(dá)開(kāi)發(fā)Web開(kāi)發(fā)服務(wù)/時(shí),發(fā)生了意外情況,Nuxt將自動(dòng)重定向到/portal


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)