vercel / micro-dev

The development environment for `micro`
MIT License
705 stars 77 forks source link

Allow using micro-dev programmatically #89

Closed elnygren closed 5 years ago

elnygren commented 6 years ago

Hi! I wanted to submit an idea I'm using myself with ts-node-dev in a TypeScript + (Apollo) GraphQL project where I use micro as my server library.

Problem

Using a package.json script such as the following:

"start": "ts-node-dev node_modules/.bin/micro-dev -p 4000 src/server.ts",

causes the process to crash on syntax errors etc. With micro this can be fixed by programmatically using micro:

# package.json
"start": "ts-node-dev src/server.ts"

# server.ts
const server = require('micro')(handler)
server.listen(PORT)

However, as we all know (https://github.com/zeit/micro/issues/337) micro-dev does not support programmatical usage. While many of the features are CLI specific, some are not.

Solution

With this PR in place, one can do something like:

const PORT = process.env.PORT || 4000

if (process.env.NODE_ENV === 'development') {
  const microDev = require('micro-dev')
  microDev({ silent: false, limit: '1mb', host: '::', port: PORT })(handler)
} else {
  const server = require('micro')(handler)
  server.listen(PORT)
}

Comments

It nothing else, this might act as a good reference for other micro & TypeScript users!

Cheers :)

qndrey commented 5 years ago

Would be nice to release this change. Really appreciated.

brandonpsmith commented 5 years ago

Please release this change. Much appreciated!

frattaro commented 5 years ago

Since this isn't published yet, someone should add another PR to return the server object from the index module, so that you can programmatically call:

  server.close(function () {
    console.log('Server shutdown.')
    process.exit()
  })
ghost commented 5 years ago

Could we get a release with this? Now that next includes an API system - it would be really nice to include dev output via the next runtime.

nathanredblur commented 4 years ago

please release this change :) thanks