How to import a single-spa in-browser utility module into a TypeScript parcel projects

148 views Asked by At

I have 3 TypeScript projects below:

root-config parcel, let us call it my-app in-browser utility module, let us call it utils All the projects above were generated using the create-single-spa command.

In the utils/src/mfe-utils.tsx file, I'm exporting the emitEvent and listenEvent module as shown below:

export function emitEvent(name: string, data: any) {
  dispatchEvent(new CustomEvent(name, { detail: data }));
}

export function listenEvent(name: string, cbs: any) {
  window.addEventListener(name, cb);
}

According to the single-spa documentation, given my orgName is mfe and projectName is utils, I should be able to import the listenEvent or emitEvent module into my-app (a parcel app) like this:

import { emitEvent } from '@mfe/utils'

Since my-app project is a TypeScript project, the statement above is definitely going to throw the error below:

Cannot find module '@mfe/utils' or its corresponding type declarations.

Is there a way to fix this?

1

There are 1 answers

0
Evgeniy On

You need to add a typescript declaration file, where your module is described. Something like utils.d.ts with the content:

declare module '@mfe/utils' {
  export function emitEvent(name: string, data: any): void;
  export function listenEvent(name: string, cbs: any): void;
}

And you need to add a path to this file/folder to the tsconfig.json if it's placed somewhere out of the curent typescript scope. Let's assume this file is placed in the types folder:

{
 ... other tsconfig content
  "compilerOptions": {
    ...
    "paths": {
      "types/*": ["../types/*"]
    }
  }
}