lasso-js / lasso

Advanced JavaScript module bundler, asset pipeline and optimizer
581 stars 75 forks source link

Koa Middleware is broken #220

Open Eldar-X opened 7 years ago

Eldar-X commented 7 years ago

app.use(require('lasso/middleware/koa').serveStatic({)); Result is : "Cannot find module 'lasso/middleware/koa'" because in this path there isn't index.js

app.use(require('lasso/middleware/koa/serveStatic')({}))! Result is:
var myLasso = options.lasso || lasso.getDefaultLasso(); ^ TypeError: lasso.getDefaultLasso is not a function at module.exports (/Users/eldar-x/Documents/Projects/NodeJs/kaya-balloons-new/node_modules/lasso/middleware/koa/serveStatic.js:15 :42)

cking commented 7 years ago

I stumbled upon the same problem, right now I'm using my own, modified middleware for it It's using koa-send instead of send and I dropped the polyfills, as I am using Node 8.4. YMMV

const lasso = require('lasso')
const send = require('koa-send')
const extend = Object.assign

function notFound () {
  this.error(404)
}

exports.serveStatic = function (options) {
  options = options || {}

  const myLasso = options.lasso || lasso.getDefaultLasso()
  const config = myLasso.config

  const outputDir = config.outputDir
  const urlPrefix = config.urlPrefix
  let routePrefix = urlPrefix
  if (!routePrefix.endsWith('/')) {
    routePrefix += '/'
  }

  if (!outputDir || !urlPrefix) {
    return async (ctx, next) => next()
  }

  const sendOptions = {
    fallthrough: false,
    redirect: false,
    index: undefined
  }

  if (options.sendOptions) {
    extend(sendOptions, options.sendOptions)
  }

  sendOptions.root = outputDir

  return function (ctx, next) {
    const req = ctx.request,
      res = ctx.response

    const path = req.path
    if (!path.startsWith(routePrefix) || (req.method !== 'GET' && req.method !== 'HEAD')) {
      return next()
    }

    const filePath = path.substring(routePrefix.length)

    // create send stream
    return send(ctx, filePath, sendOptions)
  }
}