mocks-server / main

Node.js mock server running live, interactive mocks in place of real APIs
https://www.mocks-server.org
Apache License 2.0
281 stars 14 forks source link

Support TypeScript without the need for Babel #490

Open aaronb-reach opened 3 months ago

aaronb-reach commented 3 months ago

Hi, first off a big thanks for mocks-server, its really neat and Ive enjoyed integrating it into our setup.

What I would love though is to be able to use it with .ts files without installing any babel deps. Currently ive got it working by installing these 3 additional deps:

@babel/preset-env
@babel/preset-typescript
@types/babel__preset-env

This is ok but it would be better if i could have the option to use ts-node instead to do the transpilation. A lot of the time this dep is already installed for TS projects, so it would make integrating mocks-server even more seamless.

Let me know what you think. Cheers!

aaronb-reach commented 3 months ago

If anyone is interested, I have been able to find a way to use mocks-server with .ts files without babel by using the JavaScript API to programmatically create the server:

mocks/server.ts

/* eslint-disable */
// @ts-nocheck
import { createServer } from "@mocks-server/main";

import collections from "./collections";
import routes from "./routes";

const server = createServer();

const selectedCollection = process.env.SELECTED_MOCKS_COLLECTION ?? "base";
server.mock.collections.select(selectedCollection);

server.start().then(async () => {
    const { loadRoutes, loadCollections } = server.mock.createLoaders();

    loadRoutes(routes);
    loadCollections(collections);
})

Add this block to tsconfig.json to ensure ts-node can correctly run the ts at runtime. The tsconfig-paths dep is just so our import aliasing still worked but others may not need this

"ts-node": {
  "compilerOptions": {
    "module": "commonjs"
  },
  "require": ["tsconfig-paths/register"]
},

Package.json script: npx ts-node mocks/server.ts

Its annoying having to disable eslint and type checking within mocks/server.ts, but this is not so bad because its just this one small file that will not need editing much.

+1000 for official types to be bundled with mocks-server