Home > database >  X is not exported from Y in npm run build
X is not exported from Y in npm run build

Time:11-25

I have a React Typescript project and use Craco. I have a CommonJS repo bundle which I want to integrate inside 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 something with the Webpack on craco build and other types of JS maybe?

CodePudding user response:

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())
  

CodePudding user response:

You can export the classes this way

    class A {
      test() {
        console.log("A");
      }
    }
    
    
    class B {
      test() {
        console.log("B");
      }
    }
    
    export default {
      A,
      B
    };

And import it:

import test from "./test";
const bbb = new test.B();

You can read more about how to export/import modules here

  • Related