Deno 스크립트에서 ESM 모듈 추출

7899 단어 denonodeesmwebdev
이것은 Getting Started with Deno에 대한 나의 최근 게시물에 대한 또 다른 후속 조치입니다.

크롤러 코드를 자체 코드ESM module로 추출하여 Node.js 또는 브라우저에서도 사용할 수 있도록 하는 것이 합리적이라고 생각했습니다.

결과API는 매개변수로 parse5 및 가져오기를 기대하기 때문에 약간 보기 흉하지만 작동합니다.

/**
 * @param {URL} rootURL
 * @param {boolean} noRecurse
 * @param {boolean} quiet
 * @param {function} parse5 - transitive dependency
 * @param {function} fetch - native or npm package
 * @param {Object} fetchOpts options passed to fetch - optional
 * @returns {Object} map of url -> { url, status, in, [error] }
 */
export default async function scanurl(rootURL, noRecurse, quiet, parse5, fetch, fetchOpts) {


브라우저에서 ESM 모듈 호출



https://deno-hello.jldec.me/에서 자신의 브라우저 내에서 모듈을 실행할 수 있습니다.



이 페이지는 인라인에서 모듈을 가져오는 방법을 보여줍니다<script type="module">.

<script type="module" id="code">
import scanurl from './scanurl.mjs';
import parse5 from 'https://cdn.skypack.dev/parse5';
...
</script>


일반적인 브라우저 CORS 제한은 ESM 모듈과 fetch() 호출에도 적용됩니다. 이 경우 'scanurl'은 동일한 출처의 상대 경로를 사용하여 가져오고 'parse5'는 https://www.skypack.dev/을 사용하여 가져옵니다.

노드와 함께 scanode ESM 모듈 사용



npm에 패키지로 scanode을 게시했습니다. Node가 있는 경우 'npx'로 실행하거나 'npm install'을 사용하여 설치할 수 있습니다.

$ npx scanode https://jldec.me
npx: installed 3 in 0.987s
parsing /
...
14 pages scanned.
🎉 no broken links found.


node_example/test-scan.js 에서와 같이 자신의 코드에서 모듈 API를 호출할 수도 있습니다.

import fetch from 'node-fetch';
import parse5 from 'parse5';
import scanode from 'scanode';

const result = await scanode(
  new URL('https://jldec.me'),
  false, // noRecurse
  false, // quiet
  parse5,
  fetch
);


'parse5' 및 'node-fetch'에 대한 가져오기를 확인하십시오. 이들은 scanode에 대한 package.json에 종속성으로 포함됩니다.

{
  "name": "scanode",
  "version": "2.0.1",
  "description": "ESM module - crawls a website, validating that all the links on the site which point to the same orgin can be fetched.",
  "main": "scanurl.mjs",
  "bin": {
    "scanode": "./bin/scanode.mjs"
  },
  "dependencies": {
    "node-fetch": "^2.6.1",
    "parse5": "^6.0.1"
  }
  ...


그래서 이 사진에 무슨 문제가 있나요?



논의한 바와 같이before NPM 에코시스템은 ESM 모듈보다 먼저 출시되었으므로 두 세계가 함께 원활하게 작동하지 않습니다. Node.js 프로그램은 NPM에 없는 ESM 모듈을 쉽게 로드할 수 없습니다. 한편, 브라우저는 package.json 또는 node_modules 디렉토리에 대해 아무것도 모릅니다.

ESM 모듈이 다른 모듈에 의존하는 경우 URL 또는 상대 경로와 함께 'import' 문을 사용합니다. Node.js는 이러한 하위 모듈이 NPM 패키지 이름으로 참조될 것으로 예상합니다.

그 결과 다른 모듈에 의존하는 모듈은 추가 변환 단계 없이는 두 세계 간에 이식할 수 없습니다import map.

이것이 현재 위의 API가 parse5 모듈 종속성을 매개변수로 기대하는 이유입니다.

The big question is whether the NPM ecosystem will evolve to support nested ESM modules, or whether some other organization with a workable trust model will emerge to replace it.



문제가 있는 곳에 기회가 있다!

🚀

좋은 웹페이지 즐겨찾기