vite#ServerPlugin TypeScript Examples

The following examples show how to use vite#ServerPlugin. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: serverPlugin.ts    From vite-plugin-react with MIT License 6 votes vote down vote up
reactRefreshServerPlugin: ServerPlugin = ({ app }) => {
  const runtimePath = require.resolve(
    'react-refresh/cjs/react-refresh-runtime.development.js'
  )
  // shim the refresh runtime into an ES module
  const runtimeCode = `
const exports = {}
${fs.readFileSync(runtimePath, 'utf-8')}
${debounce.toString()}
exports.performReactRefresh = debounce(exports.performReactRefresh, 16)
export default exports
`

  app.use(async (ctx, next) => {
    // serve react refresh runtime
    if (ctx.path === runtimePublicPath) {
      ctx.type = 'js'
      ctx.status = 200
      ctx.body = runtimeCode
      return
    }

    await next()

    if (ctx.response.is('html') && ctx.body) {
      const html = (await readBody(ctx.body))!
      if (injectScriptToHtml) {
        ctx.body = injectScriptToHtml(html, globalPreamble)
      } else {
        // < 0.20.2
        ctx.body = globalPreamble + html
      }
    }
  })
}