简体   繁体   中英

How to add types to module federation component in React

I'm trying to set the type of a custom component, which is exposed via the Webpack module federation. The expose and the usage working fine but Typescript is complaining about the type of the component.
I have a "frame"-module which exposes a Sidebar component. This is used inside my "App"-module.

            new ModuleFederationPlugin({
                name: 'app',
                filename: 'remoteEntry.js',
                remotes: {
                    frame: 'frame@http://localhost:3000/remoteEntry.js',
                },
   import Sidebar from 'frame/Sidebar'  //<- Cannot find module 'frame/Sidebar' or its corresponding type declarations.

I've tried several things to declare the type inside the "App"-module. I've created a @types folder inside my src folder. Inside this I've created two more folders "frame/Sidebar" and inside there an index.d.ts

import { VFC } from 'react'

declare module 'frame/Sidebar' {
    const Sidebar: VFC
    export default Sidebar
}

I've tried to move the file to different levels inside the @types folder, renamed it to frame.d.ts , tried a different declaration

declare module 'frame' {

    const Sidebar: VFC
    export { Sidebar }
}

But nothings works. I don't know, if typescript even recognizes my declaration, but the documentation states: "By default all visible ”@types” packages are included in your compilation.". So somehow my declaration is wrong.
Can anybody help me to correctly declare the type for this component?

I've found my problem. It seems like imports should be listed inside the declare module and not before. Types on the other hand can be defined outside. So this is the correct notation inside the src/@types/frame/Sidebar/index.d.ts file:

type SidebarProps = {
 ...
}

declare module 'frame/Sidebar' {

    import { VFC } from 'react'

    const Sidebar: VFC<SidebarProps>
    export default Sidebar
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM