readmeio/api

Cannot be used with create-react-app out-of-the-box

Closed this issue · 2 comments

Today I created a new React project using:

npx create-react-app my-app --template typescript

Afterwards I generated a TypeScript SDK using your "api" package with the following command:

npx api install https://dash.readme.com/api/v1/api-registry/19r2qk39lisu32yg

I am now trying to import the generated SDK (@api/southpole) using the following code:

import api from '@api/southpole';

const apiToken = 'top-secret';
api.auth(apiToken);

api.lookupEnergyEmission().then((data) => console.log(data));

Unfortunately, it fails with the following output:

ERROR in ./.api/apis/southpole/index.ts 3:12
Module parse failed: Unexpected token (3:12)
File was processed with these loaders:
 * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| __webpack_require__.$Refresh$.runtime = require('C:/dev/southpolecarbon/calculate-api-demo/node_modules/react-refresh/runtime.js');
| 
> import type * as types from './types';
| import type { ConfigOptions, FetchResponse } from 'api/dist/core';
| import Oas from 'oas';

webpack compiled with 1 error and 1 warning

I guess the problem is that @api/southpole is a symlink to .api/apis/southpole on my local disk and the .api/apis/southpole directory only contains pure TypeScript files (no compiled JavaScript) that the webpack setup of "create-react-app" does not compile using an appropriate loader.

Do you have a recipe how to solve this? Would it be possible to emit JS files when generating the SDK using your codegen?

I have been able to resolve most of the issues by specifying the following in my webpack config:

externals: {
  'fs': '{}',
  'fs-extra': '{}',
  'http': '{}',
  'https': '{}',
  'path': '{}',
  'stream': '{}',
  'url': '{}',
  'util': '{}',
}

Apologies for the delay on responding to you on this one, but when running npx api install it'll prompt you for a language target. If you select JS it'll emit a JS SDK with TS types alongside it, which should work for your usecase.