Node.js 및 esbuild: cjs와 esm 혼합에 주의하세요.
TL;DR
esbuild를 사용하여 cjs 및 esm 진입점이 혼합된 npm 패키지에 의존하는 --platform=node로 코드를 번들링하는 경우 다음 경험 법칙을 사용하세요.
- --bundle을 사용하는 경우 --format을 cjs로 설정하세요. 이는 최상위 대기 기능이 있는 esm 모듈을 제외한 모든 경우에 작동합니다.
- --format=esm을 사용할 수 있지만 이와 같은 폴리필이 필요합니다.
- --packages=external을 사용하는 경우 --format을 esm으로 설정하세요.
cjs와 esm의 차이점이 궁금하다면 Node.js: cjs, 번들러, esm의 간략한 역사를 살펴보세요.
징후
--platform=node를 사용하여 esbuild 번들 코드를 실행할 때 다음 런타임 오류 중 하나가 발생할 수 있습니다.
Error: Dynamic require of "<module_name>" is not supported
Error [ERR_REQUIRE_ESM]: require() of ES Module (...) from (...) not supported. Instead change the require of (...) in (...) to a dynamic import() which is available in all CommonJS modules.
원인
다음 제한 사항 중 하나로 인해 발생합니다.
- esbuild의 esm을 cjs로(또는 그 반대로) 변환합니다.
- Node.js cjs/esm 상호 운용성.
분석
esbuild는 esm과 cjs 간의 변환 기능이 제한되어 있습니다. 또한 esbuild에서 지원되는 일부 시나리오는 Node.js 자체에서는 지원되지 않습니다. esbuild@0.24.0 기준으로 다음 표에 지원되는 내용이 요약되어 있습니다.
Format | Scenario | Supported? |
---|---|---|
cjs | static import | Yes |
cjs | dynamic import() | Yes |
cjs | top-level await | No |
cjs | --packages=external of esm entry point | No* |
esm | require() of user modules** | Yes*** |
esm | require() of node:* modules | No**** |
esm | --packages=external of cjs entry point | Yes |
* esbuild에서는 지원되지만 Node.js에서는 지원되지 않습니다
** npm 패키지 또는 상대 경로 파일을 나타냅니다.
*** 사용자 모듈은 몇 가지 주의 사항과 함께 지원됩니다. __dirname 및 __filename은 폴리필 없이는 지원되지 않습니다.
**** node:* 모듈은 동일한 폴리필로 지원될 수 있습니다.
다음은 폴리필을 사용하지 않은 이러한 시나리오에 대한 자세한 설명입니다.
npm 패키지
다음 예제 npm 패키지를 사용합니다.
정적 가져오기
정적 임포트가 있는 esm 모듈:
Error: Dynamic require of "<module_name>" is not supported
동적 가져오기
비동기 함수 내에 동적 import()가 있는 esm 모듈:
Error [ERR_REQUIRE_ESM]: require() of ES Module (...) from (...) not supported. Instead change the require of (...) in (...) to a dynamic import() which is available in all CommonJS modules.
최상위 대기
동적 import() 및 최상위 수준 wait가 있는 esm 모듈:
import { version } from "node:process"; export function getVersion() { return version; }
필요하다
require() 호출이 있는 cjs 모듈:
export async function getVersion() { const { version } = await import("node:process"); return version; }
--format=cjs
다음 인수를 사용하여 esbuild를 실행합니다.
const { version } = await import("node:process"); export function getVersion() { return version; }
그리고 다음 코드:
const { version } = require("node:process"); exports.getVersion = function() { return version; }
정적 가져오기
잘 실행되는 다음을 생성합니다.
esbuild --bundle --format=cjs --platform=node --outfile=bundle.cjs src/main.js
동적 가져오기()
잘 실행되는 다음을 생성합니다.
import { getVersion } from "{npm-package}"; (async () => { // version can be `string` or `Promise<string>` const version = await getVersion(); console.log(version); })();
동적 import()가 cjs 모듈에서도 허용되기 때문에 require()로 변환되지 않는다는 점에 유의하세요.
최상위 수준 대기
다음 오류로 인해 esbuild가 실패합니다.
// node_modules/static-import/index.js var import_node_process = require("node:process"); function getVersion() { return import_node_process.version; } // src/main.js (async () => { const version2 = await getVersion(); console.log(version2); })();
--패키지=외부
모든 npm 패키지에서 --packages=external을 사용하면 성공합니다.
// (...esbuild auto-generated helpers...) // node_modules/dynamic-import/index.js async function getVersion() { const { version } = await import("node:process"); return version; } // src/main.js (async () => { const version = await getVersion(); console.log(version); })();
생산품:
[ERROR] Top-level await is currently not supported with the "cjs" output format node_modules/top-level-await/index.js:1:20: 1 │ const { version } = await import("node:process"); ╵ ~~~~~
그러나 Nodes.js는 cjs 모듈이 esm 모듈을 가져오는 것을 허용하지 않기 때문에 모두 실행되지 않습니다.
esbuild --packages=external --format=cjs --platform=node --outfile=bundle.cjs src/main.js
--format=esm
이제 다음 인수를 사용하여 esbuild를 실행합니다.
var npm_package_import = require("{npm-package}"); (async () => { const version = await (0, npm_package_import.getVersion)(); console.log(version); })();
사용자 모듈의 require()
src/main.js
/(...)/bundle.cjs:1 var import_static_import = require("static-import"); ^ Error [ERR_REQUIRE_ESM]: require() of ES Module /(...)/node_modules/static-import/index.js from /(...)/bundle.cjs not supported. Instead change the require of index.js in /(...)/bundle.cjs to a dynamic import() which is available in all CommonJS modules.
잘 실행되는 다음을 생성합니다.
esbuild --bundle --format=esm --platform=node --outfile=bundle.mjs src/main.js
node:* 모듈의 require()
src/main.js
const { getVersion } = require("static-import"); console.log(getVersion());
다음을 생성합니다.
// (...esbuild auto-generated helpers...) // node_modules/static-import/index.js var static_import_exports = {}; __export(static_import_exports, { getVersion: () => getVersion }); import { version } from "node:process"; function getVersion() { return version; } var init_static_import = __esm({ "node_modules/static-import/index.js"() { } }); // src/main.js var { getVersion: getVersion2 } = (init_static_import(), __toCommonJS(static_import_exports)); console.log(getVersion2());
그러나 실행에 실패합니다:
import { getVersion } from "require"; console.log(getVersion());
--패키지=외부
cjs 진입점이 있는 패키지를 포함하여 모든 npm 패키지에서 --packages=external을 사용하면 성공합니다. 예:
// (...esbuild auto-generated helpers...) var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x + '" is not supported'); }); // (...esbuild auto-generated helpers...) // node_modules/require/index.js var require_require = __commonJS({ "node_modules/require/index.js"(exports) { var { version } = __require("node:process"); exports.getVersion = function() { return version; }; } }); // src/main.js var import_require = __toESM(require_require()); console.log((0, import_require.getVersion)());
함께:
src/index.js
Error: Dynamic require of "node:process" is not supported
esm 모듈이 cjs 진입점을 사용하여 npm 패키지를 가져올 수 있기 때문에 거의 그대로 실행되는 출력을 생성합니다.
esbuild --packages=external --format=esm --platform=node --outfile=bundle.mjs src/main.js
결론
이 게시물이 현재와 미래의 esbuild 출력 문제를 해결하는 데 도움이 되기를 바랍니다. 아래에서 여러분의 생각을 알려주세요!
위 내용은 Node.js 및 esbuild: cjs와 esm 혼합에 주의하세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

JavaScript는 현대 웹 개발의 핵심 언어이며 다양성과 유연성에 널리 사용됩니다. 1) 프론트 엔드 개발 : DOM 운영 및 최신 프레임 워크 (예 : React, Vue.js, Angular)를 통해 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축합니다. 2) 서버 측 개발 : Node.js는 비 차단 I/O 모델을 사용하여 높은 동시성 및 실시간 응용 프로그램을 처리합니다. 3) 모바일 및 데스크탑 애플리케이션 개발 : 크로스 플랫폼 개발은 개발 효율을 향상시키기 위해 반응 및 전자를 통해 실현됩니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

이 기사에서는 Contrim에 의해 확보 된 백엔드와의 프론트 엔드 통합을 보여 주며 Next.js를 사용하여 기능적인 Edtech SaaS 응용 프로그램을 구축합니다. Frontend는 UI 가시성을 제어하기 위해 사용자 권한을 가져오고 API가 역할 기반을 준수하도록합니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.
