@adultswim/express-includes-middleware
TypeScript icon, indicating that this package has built-in type declarations

0.2.1 • Public • Published

@adultswim/express-includes-middleware

Express middleware for loading static include files

Installation

npm install @adultswim/express-includes-middleware

Dependencies

  • axios ^0.18.0
  • html-minifier ^3.5.12
  • p-memoize ^1.0.0

API

CommonJS:

const { includesMiddleware } = require('@adultswim/express-includes-middleware')

TypeScript:

import includesMiddleware from '@adultswim/express-includes-middleware'

includesMiddleware(options)

Returns a middleware function for fetching and attaching site includes to res.locals on each request.

Options

baseURL

Required

Type: number

The base URL to be prepended to all include paths unless the include path is absolute.

Example: https://www.adultswim.com

maxAge

Type: number

Milliseconds until the cache expires. Caching is disabled unless this is provided.

minify

Type: boolean or an html-minifier options object

Default: false

Controls the minification of includes. If true is passed the default minification options will be:

{
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true,
    removeComments: true,
}
paths

Required

Type: object | string[]

Either a list of key/values where the key is the name on res.locals.includes and the value is a string of the path to the include, or an array of path strings where the path string will also be the resulting key on res.locals.includes.

All paths are prefixed with the baseURL option.

Example with Object:

{
  legal: '/tools/includes/legal.html'
}

will result in res.locals.includes.legal being "/tools/includes/legal.html"

Example with Array:

[
    '/tools/includes/global-nav.html'
]

will result in res.locals.includes["/tools/includes/global-nav.html"] being "/tools/includes/global-nav.html"

Example Usage

Setup the middleware on the app route:

import express from 'express';
import includesMiddleware from '@adultswim/express-includes-middleware';

const app = express();

// load includes on all GET requests
app.get('*', includesMiddleware({
  baseURL: 'https://www.adultswim.com',
  maxAge: 300000, // cache includes for 5 minutes
  minify: true,
  paths: {
    // content will be available as raw text on res.locals.includes.nav:
    'nav': '/tools/includes/global-nav.html',
    'footer': '/tools/includes/legal.html',
  }
}), (req, res) => {
  res.render('client');
});

Then output the result in the view:

// client.pug
// res.locals is automatically provided to the view by Express

doctype html
html
  head
    title My App
   body
     != includes.nav
     #app
     != includes.footer

Readme

Keywords

none

Package Sidebar

Install

npm i @adultswim/express-includes-middleware

Weekly Downloads

2

Version

0.2.1

License

MIT

Unpacked Size

7.86 kB

Total Files

5

Last publish

Collaborators

  • ajliv
  • jhumbug