Allow CLI to use any kind of require-able module
This would allow the CLI to load the DB from any compile-to-JS language directly, removing the need to do it programatically as long as the necessary compiler is loaded.
The NODE_OPTIONS env var allows us to pass opts directly to the nodejs binary when running CLI applications. This way, we can actually allow the CLI to directly load TypeScript files, or CoffeeScript files, or Babel, or whatever else.
I already tried this modification and it works nicely with TypeScript (using ts-node) by doing:
NODE_OPTIONS="--require ts-node/register" json-server db.ts
And having db.ts with:
import * as casual from 'casual'
import { Item } from './src/interfaces'
function generateItem(): Item {
return {
docType: 'item',
uid: casual.uuid,
owner: casual.first_name.toLowerCase(),
name: casual.name,
graphics: {
images: [
`https://loremflickr.com/1280/720`,
`https://loremflickr.com/640/360`
]
}
}
}
export = () => ({
items: new Array(100).map(generateItem)
})
Related to https://github.com/typicode/json-server/issues/833. Not sure why the tests are not passing, but it seems unrelated to these changes.
Just fixed a missing path.resolve() in the changes I did and now the tests are passing fine. I'm using the CLI by installing this package from my fork directly from Github, which means I have to also commit the built files (which I'm doing in a separate branch). It would really be helpful for me and many other people if this got merged and published :) Would probably be a good idea to add in the Readme a note about using NODE_OPTIONS="-r ts-node/register" json-server ....
Added another improvement: Now is.Module() will only check the 'MODULE_NOT_FOUND' error to see if the source is a module or not. Other errors will be swallowed when checking but it will still consider the source to be a module. These other errors are, for example, TypeScript compilation errors on the required file. Then, being considered a module, the CLI will proceed to require it and then it will fail with the actual compilation error, which gets nicely printed out and helps you fix it. I expect it to do the same for CoffeeScript and Babel, etc, in the same way that it would do it with a malformed plain JS file - showing the error output when requiring it.
This pr is over a year old. Tests are passing, no conflicts with base branch. Can it be merged?
I think it's fine to merge it. It doesn't interfere with the rest of the functionality or anything. I think a note about the usage of it should be added on the README though.