Unexpected “Uncaught TypeError: XXX is not a constructor” errors with Babel and ES6

前端 未结 6 492
無奈伤痛
無奈伤痛 2020-12-29 19:04

I am giving a try to Webpack, and am giving a try to the instructions in this tutorial, give or take a few custom things.

This is simple code, really, but I\'m quite

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 19:37

    Although this is not the cause of your particular issue, I ran into a very similar problem when trying to rip babel out of an existing node app that was using ES6's import and export syntax, so this post is to help out anyone else struggling with this in the future.

    Babel will resolve any circular dependencies between one module and another, so you can use ES6's import and export with reckless abandon. However, if you need to get rid of babel and use native node, you will need to replace any import and exports with require. This can reintroduce a latent circular reference issues that babel was taking care of in the background. If you find yourself in this situation, look for an area in your code that looks like this:

    File A:

    const B = require('B');
    
    class A {
      constructor() {
        this.b = new B();
      }
    }
    module.exports = A;
    

    File B:

    const A = require('A'); // this line causes the error
    
    class B {
      constructor() {
        this.a = new A();
      }
    }
    module.exports = B;
    

    There are several different ways to resolve this issue depending on how you structured your code. The easiest way is probably to pass B a reference to A instead of creating a new instance of class A. You could also dynamically resolve the reference when loading A. There are a myriad of other alternatives, but this is a good place to get started.

提交回复
热议问题