swc: Cannot access before initialization error in NestJs
Describe the bug
I’m using swc in a NestJs project and i’m facing the following issue when i run my unit test with jest:
ReferenceError: Cannot access 'DocumentEntity' before initialization
10 |
11 | @Entity('documents')
> 12 | export class DocumentEntity extends EntityObj {
| ^
13 | @PrimaryGeneratedColumn()
14 | id: string;
15 |
at Object.DocumentEntity (features/documents/document.entity.ts:12:14)
at Object.<anonymous> (features/documents/data/document-data.entity.ts:16:14)
at Object.<anonymous> (features/documents/document.entity.ts:12:29)
at Object.<anonymous> (features/resources/resource.entity.ts:13:25)
at Object.<anonymous> (features/resources/resources-db.store.ts:10:25)
at Object.<anonymous> (features/resources/resources-db.store.spec.ts:5:27)
I think the error is caused by the automapper library which i use in the document-data.entity.ts
:
Input code
@Entity('documents-data')
export class DocumentDataEntity {
@PrimaryColumn()
@AutoMap()
key: string;
@PrimaryColumn({ nullable: false })
documentId?: string;
@AutoMap(() => DocumentEntity) // Think error comes from here
document?: DocumentEntity;
}
Config
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": false,
"decorators": true,
"dynamicImport": true
},
"target": "es2021",
"transform": {
"legacyDecorator": true,
"decoratorMetadata": true
}
},
"module": {
"type": "commonjs",
"noInterop": false
}
}
FYI, it works with the swc config "target": "es5"
but then i’ve got code coverage issues
Playground link
No response
Expected behavior
I’m expecting the test to run correctly
Actual behavior
No response
Version
1.13.19
Additional context
No response
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 10
- Comments: 15 (1 by maintainers)
I am getting the same error after upgrading swc. I am using ts-node with swc, via my tsconfig.json
This error is happening pretty much everywhere there is a typescript reference to a class type. For example, in my entity class, the fields will reference typescript types of other entity classes.
It seems to be a problem with the loader not understanding that these are merely type references and not instances of the class object. I can remove the error by the following, but I have to do it all throughout my code base!
Create a trivial typescript type
Then change all my class type references from
Foo
toType<Foo>
. For example, if I have a field such asthen it becomes
When I do this, the circular dependency is resolved. It seems to force the class reference to be treated as just a type, rather than an actual class object instance. Very strange,
This issue has been automatically closed because it received no activity for a month and had no reproduction to investigate. If you think this was closed by accident, please leave a comment. If you are running into a similar issue, please open a new issue with a reproduction. Thank you.