웹사이트 검색

javascript - ESM 변경으로 인해 제 NestJS 프로젝트에서 충돌이 발생하고 있습니다


저는 nestjs-cashify의 저자입니다. 저는 제 패키지와 그 기본 패키지들을 업데이트하기로 결정했습니다. 제가 사용 중인 핵심 패키지 중 하나를 업데이트한 후 몇 가지 문제를 겪고 있습니다. 제 패키지의 ts 설정이 es6로 되어 있고 es2020가 아니기 때문입니다. (다시 말해, 제가 사용하고 있는 패키지의 새 버전은 최근에 es2020로 변경되었습니다)

내가 내 패키지를 일반 NestJS 프로젝트(내 예제 폴더)에서 사용하고 싶을 때, 나는 다음과 같은 오류들을 받습니다:

/home/vahidnajafi/repos/nestjs-cashify/dist/cashify.module.js:21
const cashify_1 = require("cashify");
                  ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/vahidnajafi/repos/nestjs-cashify/node_modules/cashify/dist/index.js from /home/vahidnajafi/repos/nestjs-cashify/dist/cashify.module.js not supported.
Instead change the require of index.js in /home/vahidnajafi/repos/nestjs-cashify/dist/cashify.module.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/home/vahidnajafi/repos/nestjs-cashify/dist/cashify.module.js:21:19)
    at Object.<anonymous> (/home/vahidnajafi/repos/nestjs-cashify/dist/index.js:18:14)
    at Object.<anonymous> (/home/vahidnajafi/repos/nestjs-cashify/example/dist/app.module.js:12:26)
    at Object.<anonymous> (/home/vahidnajafi/repos/nestjs-cashify/example/dist/main.js:4:22) {
  code: 'ERR_REQUIRE_ESM'
}

이것은 내 프로젝트가 "es6"로 설정되어 있고 빌드할 때 ES 모듈에 대해 "require"를 사용하기 때문에 말이 됩니다(코어 모듈은 새 버전부터 이제 ESM입니다): 다음은 오류입니다: /cashify.module.js에서 /index.js의 ES 모듈 require()는 지원되지 않습니다.

그럼 저도 제 프로젝트를 'es2020'으로 설정하기로 결정했습니다. 이제 이 오류는 사라졌습니다(제 빌드 결과에서 더 이상 require를 사용하지 않고 import 문을 사용하기 때문에).

내 예제 폴더(일반 NestJS 프로젝트)에서, 내가 내 패키지를 테스트하고 있는 곳에서, 이 설정은 다음과 같이 되어 있습니다: "target": "es2017",

이제 다음 오류가 표시됩니다:

SyntaxError: Unexpected token 'export'

중요 참고:

제 예제 프로젝트의 설정을 변경하는 것이 좋은 생각은 아니지만(모든 NestJS 개발자가 이것을 해야 하기 때문에), 그래도 고치려고 시도했습니다. 저도 그것을 es2020으로 변경했습니다.

이번에는 다음과 같은 오류가 발생합니다:

(node:89687) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
/home/vahidnajafi/repos/nestjs-cashify/example/dist/main.js:1
import { NestFactory } from '@nestjs/core';
^^^^^^

SyntaxError: Cannot use import statement outside a module

저는 또한 패키지.json 파일에서 "type": "module"을 설정하려고 시도했지만(오류 메시지에 언급된 대로) 그 다음에 이 오류가 나타났습니다:

internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/vahidnajafi/repos/nestjs-cashify/example/dist/app.module' imported from /home/vahidnajafi/repos/nestjs-cashify/example/dist/main.js

무슨 생각 있어?

답변 #1

당신은 async import로 모듈을 로드해야 합니다.

https://nodejs.org/api/esm.html#esm_interoperability_with_commonjs