Search code examples
reactjswebpackreact-typescript

How to export and import modules in TypeScript


I have a React Typescript project and use Craco. I have a CommonJS repo bundle which I want to integrate into the project.

Using Craco start, the project works and there are no problems. On the build however, the error is:

Attempted import error: 'B' is not exported from './test' (imported as 'test').

I tried simplifying the problem by using a test and basically this is what we have.

File: ./test.js

class A {

    test() {
        console.log('a')
    }
}

module.exports = A


class B {

    test() {
        console.log('a')
    }
}

module.exports = B

module.exports = {
    A,
    B
}

File: ./service.ts

import * as test from './test'
console.log(test.B)

I think it is something with the Webpack on Craco build and other types of JS maybe?


Solution

  • wrong export you need to change your code like this

    Page 1)

     export class A {
            
                test() {
                    console.log('a')
                }
            }
            
            
            
        export  class B {
            
                test() {
                    console.log('a')
                }
            }
    

    Page 2

        import * as test from './test'
    console.log(new test.B().test())