Koa Parcel Middleware

1.0.3 · abandoned · verified Tue Apr 21

koa-parcel-middleware is a Koa.js middleware designed to integrate the Parcel bundler's functionality directly into a Koa application. This enables developers to serve their UI applications from the same Koa server, leverage Parcel's development server features like Hot Module Replacement (HMR) within an existing server setup, and implement advanced techniques such as server-side rendering (SSR) for isomorphic JavaScript. The package is currently at version 1.0.3, with its last release in 2019, indicating an abandoned or unmaintained status. Its primary differentiator is the seamless integration of Parcel v1's bundling capabilities with Koa's middleware stack, obviating the need for a separate Parcel dev server process.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up a Koa server with `koa-parcel-middleware` to bundle and serve a UI application. It includes Parcel v1 configuration, optional server-side rendering (SSR) integration, and static asset serving using `koa-static`.

import { createMiddleware } from 'koa-parcel-middleware'
import { promises as fs } from 'fs'
import * as path from 'path'
import * as ReactDOMServer from 'react-dom/server'
import Bundler from 'parcel-bundler'
import CombinedStream from 'combined-stream'
import Koa from 'koa'
import serveStatic from 'koa-static'

// Your Parcel application's unbuilt entry point
const ENTRY_FILENAME = path.resolve(__dirname, 'index.html')
const isDev = process.env.NODE_ENV === 'development'

async function start () {
  const app = new Koa()
  // Your Parcel application's built entry point
  const outFile = path.resolve(__dirname, 'dist', 'index.html')
  const outDir = path.resolve(__dirname, 'dist')
  const options = {
    outDir,
    outFile,
    watch: isDev,
    minify: !isDev,
    scopeHoist: false,
    hmr: isDev,
    detailedReport: isDev
  }
  const bundler = new Bundler(ENTRY_FILENAME, options)
  bundler.bundle() // Initiate Parcel bundling

  const staticMiddleware = serveStatic(outDir)
  const parcelMiddleware = createMiddleware({
    bundler,
    renderHtmlMiddleware: async (ctx, next) => {
      // Optionally wire in Server-Side Rendering (SSR) here
      const outFileBuffer = await fs.readFile(outFile)
      const [preAppEntry, postAppEntry] = outFileBuffer.toString()
        .split(/<!--.*ssr.*-->/)
      ctx.status = 200
      const htmlStream = new CombinedStream()
      ;[
        preAppEntry,
        ReactDOMServer.renderToNodeStream(/** Your React App component here **/ null),
        postAppEntry
      ].map(content => htmlStream.append(content))
      ctx.body = htmlStream
      ctx.type = 'html'
      await next()
    },
    staticMiddleware
  })

  app.use((ctx, next) => parcelMiddleware(ctx, next))
  app.listen(3000, () => console.log('Koa server with Parcel middleware running on port 3000'))
}
start().catch(console.error)

view raw JSON →