reactjstypescriptwebpackbabel-loadernpm-link

Create React App with TypeScript and NPM Link: Enums causing Module parse failed


I have a basic create-react-app TypeScript project (client). Just directory up, I have a server and a shared folder. Inside the shared folder I have a number of interfaces and enums that I share between the server and the client.

I wish to link this shared folder to both the client and server packages.

First, I went to shared and ran $ yarn link and then ran $ yarn link shared from both the client and the server folders.

The server is as happy as can be, and for the most part the client is too. However, as soon as I use one of the enums from the shared directory in the client, I get an error:

../shared/src/models/Roles.ts 4:0
Module parse failed: The keyword 'enum' is reserved (4:0)
File was processed with these loaders:
 * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
You may need an additional loader to handle the result of these loaders.
| $RefreshSetup$(module.id);
| 
> enum Roles {
|     RW_ORG = "rw_org", // can modifiy organization and it's users, nothing else

I'm importing it like so: import {Roles} from "shared"; but have tried numerous other ways as well.

I'm exporting it from the shared index.ts like so

import Roles from "./models/Roles";

export type { 
    // all of my interfaces
};
export { Roles }

All of my interfaces are usable, so I don't understand. What the hell is going on here?


Solution

  • Well, it turns out that these errors are all cause by create-react-app's default webpack.config.js. If you navigate to code node_modules/react-scripts/config/webpack.config.js you fill find a line include: paths.appSrc which basically limits Babel to the src/ folder of the react app itself.

    That means, if you've yarn linked a folder outside of it, Babel will not transpile it to normal JS, and thus React cannot use it.

    There are two hacky solutions, but I would like a better one.

    1. Manually (or via a build script) delete the include: paths.appSrc line from react-scripts every time you install a node module
    2. Make a script that copies the external directory into your React src directory every time the external directory is modified.

    I really wish there were an official way around this...