Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compiler error "ReferenceError: require is not defined in ES module scope, you can use import instead" #2925

Closed
2 of 4 tasks
yaluba1 opened this issue Apr 22, 2024 · 3 comments

Comments

@yaluba1
Copy link

yaluba1 commented Apr 22, 2024

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

I found this bug when I add Swagger to one of my services. In that one, the problem arises with a DTO 👍

export class CreateOrgDto {
    ...
    storageconf: StorageConf;
    //storageconf: string;
}

Here "StorageConf" is an Enum. It works OK when it is a string (comment one line and uncomment the other).

When creating the sample to share in the repo with the "minimum reproduction code", the issue generalised. It happens always in that code, and it is really a very basic one.

Important points:

  • tsconfig.json is set target ES2022:
"compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "target": "ES2022",
... }
  • "type": "module" in package.json

the javascript code created in "dist" for the DTO above is:

import { createRequire as _createRequire } from "module";
const __require = _createRequire(import.meta.url);
const openapi = __require("@nestjs/swagger");
export class CreateOrgDto {
    ...
    storageconf;
    static _OPENAPI_METADATA_FACTORY() {
        return { ... , storageconf: { required: true, type: () => String, enum: require("../entities/org.entity", { with: { "resolution-mode": "import" } }).StorageConf } };
    }
}

The problem is with the 'require" inside _OPENAPI_METADATA_FACTORY()

This issue may be linked to ESM Build Issues #1450 , which seems to depend on build: generate multiple formats (cjs, esm) #8736 , which points to this recent post in Joyee Cheung's Blog. I did try running with flag --experimental-require-module , but it did not make any difference.

The issue is not consistent. In the provided sample repo, it happens always.
In a larger project that I have with several independent micro-services (separated in different apps), all set to ES2022, it only happens with the one that has the DTO above, all other compile correctly. Actually, as mentioned, even this one compiles correctly if "storageconf" is of type string instead of "StorageConf" enum.

Minimum reproduction code

https://github.com/yaluba1/NestJsSwaggerBug

Steps to reproduce

  1. yarn install
  2. yarn start:dev

Expected behavior

I was expecting correct compilation. Instead. I get:

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'C:...\NestJsSwaggerBug\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///C:/.../NestJsSwaggerBug/dist/app.controller.js:26:112
at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
at ModuleLoader.import (node:internal/modules/esm/loader:329:24)
at loadESM (node:internal/process/esm_loader:28:7)
at handleMainPromise (node:internal/modules/run_main:113:12)

Package version

7.3.1

NestJS version

10.3.0

Node.js version

20.11.0

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

IDE: VsCode vs1.88.1
Package manager: yarn v4.1.1

@marklai1998
Copy link

I'm having this issue as well in my ESM output service.

The issue is with non-literal types like objects and enum, those are translated to a dynamic import by the plugin
then the replaceImportPath function explicitly replace import("somepath") to require("somepath")

typeReference = typeReference.replace('import', 'require');

typeReference: typeReference.replace('import', 'require'),

I tried to remove those two lines and it runs perfectly fine. So technically it is not blocked by the "ESM support" issue, just making it not do the string replace if the target is ESM

@marklai1998
Copy link

marklai1998 commented Jul 16, 2024

I found this package to do monkey patch on the build, not sure how to integrate it to the cli with watch mode capability

It references microsoft/TypeScript#43329 when mentioning this "require" import issue
I guess at some point TS only emit require for both ESM and CJS build, but now it is fixed, import/require is chosen based on the config
I guess for some reason the maintainer wanna keep existing behaviour and blindly replace it back to require

@kamilmysliwiec
Copy link
Member

#1450

@nestjs nestjs locked and limited conversation to collaborators Oct 24, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants