72

I'm having the following TypeScript class

export class Vehicule extends TrackableEntity {
  vehiculeId: number;
  constructor() {
    super();
    return super.proxify(this);
  }
}

my typescript target in tsconfig.json is configured as es6:

"compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
}

At runtime, here in Chrome, the code is failing with:

ReferenceError: Cannot access 'Vehicule' before initialization
    at Module.Vehicule (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:10559:100)
    at Module../src/app/domain/models/VehiculeGpsBoxInfo.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:11156:69)
    at __webpack_require__ (https://localhost:44338/runtime.js:84:30)
    at Module../src/app/domain/models/Vehicule.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:10571:78)
    at __webpack_require__ (https://localhost:44338/runtime.js:84:30)
    at Module../src/app/components/dispositifsDATI/mainDATI/listDATI/listDATI.component.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:6447:82)
    at __webpack_require__ (https://localhost:44338/runtime.js:84:30)
    at Module../src/app/components/dispositifsDATI/index.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:3053:95)
    at __webpack_require__ (https://localhost:44338/runtime.js:84:30)
    at Module../src/app/components/dispositifsDATI/dispositifsDATI.routes.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:2982:64)

I needed to change es5 to es6 to solve this other problem.


EDIT: The VehiculeGpsBoxInfo.ts file is importing Vehicule like this:

import { Vehicule } from "./Vehicule";

EDIT 2: I vould say that this may be webpack related, the way that modules are exported/imported in the genrated modules.

EDIT 3: After further research, this seems to have nothing to do with the code shown above. Started a new question about webpack and ES6.

  • Is it valid to `return` something in a `constructor`? – jlang Oct 31 '19 at 10:08
  • 2
    @jlang Please see [this](https://stackoverflow.com/questions/40961778/returning-es6-proxy-from-the-es6-class-constructor) –  Oct 31 '19 at 10:32
  • I had this issue and found out a service I was injecting had some injections missing providers. Check your tree – Polyterative May 11 '22 at 12:16

14 Answers14

93

I was getting this error due to a circular dependency, like

  • A injected with B
  • B injected with C
  • C injected with A

Removing the circular dependecy fixed this error.

Wesley Gonçalves
  • 1,985
  • 2
  • 19
  • 22
  • 8
    This is definitely relevant and helped me figure out my issue. In my case I had a service S provided by ModuleA, used internally and by ModuleB (that didn't import ModuleA). This wasn't quite the issue, but rather that service S should've been provided by ModuleC instead. – Gui Brunow Nov 10 '20 at 23:55
  • 2
    I had a circular dependency as well. Once I fixed it everything was fine again. thanks – LeonardoX Sep 13 '21 at 07:58
  • It was also my case, thank you ! – Guillaume Martin Apr 25 '23 at 08:37
67

You're probably running into this Angular issue: https://github.com/angular/angular-cli/issues/15077.

From that issue:

Hi, is there a reason why you need emitDecoratorMetadata to be true?

This TypeScript option has a fundamental design limitation with ES2015+ code and is best avoided when targeting such output. As such this is an issue with TypeScript itself and not Angular.

Angular 8+ no longer requires the option. It was also previously only required for JIT mode which is typically only used in development.

The solution is to set "emitDecoratorMetadata": false in your tsconfig.json file.

Side note: I must say, given that previous versions of the Angular CLI automatically added emitDecoratorMetadata: true, and there's no reason I can see why a dev should know that emitDecoratorMetadata should now be false, it's pretty horrible that the Angular team basically said "this isn't our problem" and closed the issue without action. This could have been easily "fixed" by adding some better documentation (as pointed out by someone in the linked issue).

Community
  • 1
  • 1
John
  • 9,249
  • 5
  • 44
  • 76
25

Note that this error can also be caused by defining two public @Injectable classes within the same .ts file.

I've tripped over this more than once when I'm just prototyping stuff locally (especially when refactoring one service into multiple).

Setting emitDecoratorMetadata: false does fix this situation as well; but in case you're in a hurry to fix something or don't want fiddle with thetsconfig.json file on a large project - it's useful to know that you might be able to fix it by just moving one of the classes into a new file.

Shorn
  • 19,077
  • 15
  • 90
  • 168
14

to find circular dependencies :

npx madge --circular --extensions ts ./

(build before)

user1568220
  • 1,018
  • 1
  • 8
  • 10
9

I ran into this due to the order of my import statements in the module. A file that also accessed the component had to be imported before the component.

mbursill
  • 2,911
  • 1
  • 32
  • 44
  • This was it for me. Thanks for throwing this in the answers! – tuffant21 Aug 30 '22 at 19:07
  • This was it for me. In my case, I did "organize imports" shortcut in VS code, and some services were imported before the AppComponent in main.ts. Making AppComponent appear first solved the problem. – aosaimy Apr 25 '23 at 22:13
  • This helped me though, in my case, the source of the error was in my library and I just moved the directive that caused the error to the top of its file. I bet I could have changed the export order in the public-api.ts as well. I can't believed it worked... seems flaky. – AndrewBenjamin Apr 30 '23 at 15:29
3

I see that in 2023 there is no correct answer, but this problem is listed high enough in google. So basically what you need to do in scenario:

  • A injected with B
  • B injected with C
  • C injected with A

Put all tree components in one separate module.ts e.g. abc.module.ts. In that file you can event simpler put all components in array like this:

export const components = [ AComponent, BComponent, CComponent, ];

and then in @NgModule {} add this array to: exports: [components], declarations: [components],

imports:[] array has all dependant components which are used by those tree. And thats it, you will be safe from ReferenceError : Cannot access 'X' before initialization

Karolis
  • 31
  • 1
2

Circular dependency is the devil!

It causes the whole dependency loop to be unresolvable by the compiler. In most cases, the errors look like you are not importing the classes at all.

Some might think that circular dependencies should only be prevented in services and modules, However, circular dependency should be prevented in all forms, even in models, components, and classes.

When you have circular dependency it's a sign that (sooner or later) you need to refactor and restructure your code. The following hints might be useful to do so. Suppose we want to remove the circular dependency between two classes A, B.

Solution 1: Union/Merge

A and B are following the very same concept and they can be merged into a single class.

Solution 2: Separation/Creation

There should be a new class C, that both A and B rely on or sits somewhere between those two.

According to my experience, in most cases, the circular dependency happens because the developer tends to merge n logics into k (k<n) classes.

  • that's why everybody is abandoning angular – Dinaiscoding Jan 06 '23 at 12:58
  • 1
    @DinaFlies Circular dependencies between modules are considered an anti-pattern because of their negative effects regardless of the platform. So it's not about angular or a specific platform. – Hamidreza Vakilian Jan 07 '23 at 12:38
  • I've missed the part I've mentioned circular dependencies. While angular has extra-complexity to deal with modules, other frameworks simply import their components where they are needed. – Dinaiscoding Jan 07 '23 at 17:25
1

In Angular 8, having entryComponents declared as an empty list in a SharedModule caused this issue for me:

entryComponents: []

After removing entryComponents, everything worked fine.

Hadrien TOMA
  • 2,375
  • 2
  • 22
  • 32
Samih A
  • 403
  • 1
  • 10
  • 15
0

In my case, I had an index.ts file that exported components from A.ts and B.ts.

B.ts tried to import from the index.ts instead of A.ts.

This caused the MJS to be emitted in the incorrect order because of the cycle:

B.ts -> index.ts -> B.ts

You can search for imports ending in from ".". This can be avoided by using a underscored prefix _index.ts (except in the root directory).

I'm posting this for others looking for other ideas that cause Cannot access 'X' before initialization. Best of luck.

0

In my case, it wasn't any circular dependency, it was a bug in an array that I export and use inside one of the components.

The array is multidimensional and I used one of the indexes without initializing it first, when I opened the project I got the error:

ReferenceError: Cannot access 'XXXModule' before initialization

I started reverting back the files one by one until I found the exact issue, but really weird how I didn't get another error explaining the wrong use of an array.

MuhammadNe
  • 674
  • 4
  • 11
  • 24
0

For those still searching for another solution to this error, I found out that I had two equal imports in a Parent Component and Child Component and that was giving me this error .

Example:

ParentComponent and ChildComponent both have this import:

import { ExampleComponent } from '../example-component/example-component.component'

The solution was to remove that one line of import in one of them and the error stop

Hope this saves someone's time

0

I ran into this when I was adding another folder / entrypoint to a library. I had multiple components and was importing one into the other. The default import path VSCode used was ./public-api. Changing it to the actual component path (../folder/file) fixed the issue.

Jadamae77
  • 828
  • 7
  • 13
0

For people landing here from a search: When you get this error in Angular 15 or above, it might be due to circular dependencies at standalone components. In that case you can fix it with forwardRef:

@Component({
  standalone: true,
  selector: 'app-b',
  templateUrl: './b.component.html',
  styleUrls: ['./b.scss'],
  imports: [
    forwardRef(() => AComponent))
  ]
})
export class BComponent implements OnInit {

}

See: https://stackoverflow.com/a/76233363/11603006

Jonathan
  • 517
  • 1
  • 6
  • 12
-5

that make sense, you are passing the local object (Vehicle) to the parent class within constructor return super.proxify(this);.

Keep in mind the local Vehicle instance has not been instantiated yet (constructor block is not finished yet), so you cannot use this object in the mean time, you need to wait the constructor to done it's job.

Jared Forth
  • 1,577
  • 6
  • 17
  • 32