679f52b138b78120671980068fe16a31118ff6fceba71a482bf7f0e7f4cc094cbeb70b51ada35001da63fb3c79477f2aeac64d8f3d1951a708027bd154d0fd 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. # mlly
  2. [![npm version][npm-version-src]][npm-version-href]
  3. [![npm downloads][npm-downloads-src]][npm-downloads-href]
  4. [![Codecov][codecov-src]][codecov-href]
  5. > Missing [ECMAScript module](https://nodejs.org/api/esm.html) utils for Node.js
  6. While ESM Modules are evolving in Node.js ecosystem, there are still
  7. many required features that are still experimental or missing or needed to support ESM. This package tries to fill in the gap.
  8. ## Usage
  9. Install npm package:
  10. ```sh
  11. # using yarn
  12. yarn add mlly
  13. # using npm
  14. npm install mlly
  15. ```
  16. **Note:** Node.js 14+ is recommended.
  17. Import utils:
  18. ```js
  19. // ESM
  20. import {} from "mlly";
  21. // CommonJS
  22. const {} = require("mlly");
  23. ```
  24. ## Resolving ESM modules
  25. Several utilities to make ESM resolution easier:
  26. - Respecting [ECMAScript Resolver algorithm](https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_resolver_algorithm)
  27. - Exposed from Node.js implementation
  28. - Windows paths normalized
  29. - Supporting custom `extensions` and `/index` resolution
  30. - Supporting custom `conditions`
  31. - Support resolving from multiple paths or urls
  32. ### `resolve` / `resolveSync`
  33. Resolve a module by respecting [ECMAScript Resolver algorithm](https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_resolver_algorithm)
  34. (using [wooorm/import-meta-resolve](https://github.com/wooorm/import-meta-resolve)).
  35. Additionally supports resolving without extension and `/index` similar to CommonJS.
  36. ```js
  37. import { resolve, resolveSync } from "mlly";
  38. // file:///home/user/project/module.mjs
  39. console.log(await resolve("./module.mjs", { url: import.meta.url }));
  40. ```
  41. **Resolve options:**
  42. - `url`: URL or string to resolve from (default is `pwd()`)
  43. - `conditions`: Array of conditions used for resolution algorithm (default is `['node', 'import']`)
  44. - `extensions`: Array of additional extensions to check if import failed (default is `['.mjs', '.cjs', '.js', '.json']`)
  45. ### `resolvePath` / `resolvePathSync`
  46. Similar to `resolve` but returns a path instead of URL using `fileURLToPath`.
  47. ```js
  48. import { resolvePath, resolveSync } from "mlly";
  49. // /home/user/project/module.mjs
  50. console.log(await resolvePath("./module.mjs", { url: import.meta.url }));
  51. ```
  52. ### `createResolve`
  53. Create a `resolve` function with defaults.
  54. ```js
  55. import { createResolve } from "mlly";
  56. const _resolve = createResolve({ url: import.meta.url });
  57. // file:///home/user/project/module.mjs
  58. console.log(await _resolve("./module.mjs"));
  59. ```
  60. **Example:** Ponyfill [import.meta.resolve](https://nodejs.org/api/esm.html#esm_import_meta_resolve_specifier_parent):
  61. ```js
  62. import { createResolve } from "mlly";
  63. import.meta.resolve = createResolve({ url: import.meta.url });
  64. ```
  65. ### `resolveImports`
  66. Resolve all static and dynamic imports with relative paths to full resolved path.
  67. ```js
  68. import { resolveImports } from "mlly";
  69. // import foo from 'file:///home/user/project/bar.mjs'
  70. console.log(
  71. await resolveImports(`import foo from './bar.mjs'`, { url: import.meta.url }),
  72. );
  73. ```
  74. ## Syntax Analyzes
  75. ### `isValidNodeImport`
  76. Using various syntax detection and heuristics, this method can determine if import is a valid import or not to be imported using dynamic `import()` before hitting an error!
  77. When result is `false`, we usually need a to create a CommonJS require context or add specific rules to the bundler to transform dependency.
  78. ```js
  79. import { isValidNodeImport } from "mlly";
  80. // If returns true, we are safe to use `import('some-lib')`
  81. await isValidNodeImport("some-lib", {});
  82. ```
  83. **Algorithm:**
  84. - Check import protocol - If is `data:` return `true` (✅ valid) - If is not `node:`, `file:` or `data:`, return `false` (
  85. ❌ invalid)
  86. - Resolve full path of import using Node.js [Resolution algorithm](https://nodejs.org/api/esm.html#resolution-algorithm)
  87. - Check full path extension
  88. - If is `.mjs`, `.cjs`, `.node` or `.wasm`, return `true` (✅ valid)
  89. - If is not `.js`, return `false` (❌ invalid)
  90. - If is matching known mixed syntax (`.esm.js`, `.es.js`, etc) return `false` (
  91. ❌ invalid)
  92. - Read closest `package.json` file to resolve path
  93. - If `type: 'module'` field is set, return `true` (✅ valid)
  94. - Read source code of resolved path
  95. - Try to detect CommonJS syntax usage
  96. - If yes, return `true` (✅ valid)
  97. - Try to detect ESM syntax usage
  98. - if yes, return `false` (
  99. ❌ invalid)
  100. **Notes:**
  101. - There might be still edge cases algorithm cannot cover. It is designed with best-efforts.
  102. - This method also allows using dynamic import of CommonJS libraries considering
  103. Node.js has [Interoperability with CommonJS](https://nodejs.org/api/esm.html#interoperability-with-commonjs).
  104. ### `hasESMSyntax`
  105. Detect if code, has usage of ESM syntax (Static `import`, ESM `export` and `import.meta` usage)
  106. ```js
  107. import { hasESMSyntax } from "mlly";
  108. hasESMSyntax("export default foo = 123"); // true
  109. ```
  110. ### `hasCJSSyntax`
  111. Detect if code, has usage of CommonJS syntax (`exports`, `module.exports`, `require` and `global` usage)
  112. ```js
  113. import { hasCJSSyntax } from "mlly";
  114. hasCJSSyntax("export default foo = 123"); // false
  115. ```
  116. ### `detectSyntax`
  117. Tests code against both CJS and ESM.
  118. `isMixed` indicates if both are detected! This is a common case with legacy packages exporting semi-compatible ESM syntax meant to be used by bundlers.
  119. ```js
  120. import { detectSyntax } from "mlly";
  121. // { hasESM: true, hasCJS: true, isMixed: true }
  122. detectSyntax('export default require("lodash")');
  123. ```
  124. ## CommonJS Context
  125. ### `createCommonJS`
  126. This utility creates a compatible CommonJS context that is missing in ECMAScript modules.
  127. ```js
  128. import { createCommonJS } from "mlly";
  129. const { __dirname, __filename, require } = createCommonJS(import.meta.url);
  130. ```
  131. Note: `require` and `require.resolve` implementation are lazy functions. [`createRequire`](https://nodejs.org/api/module.html#module_module_createrequire_filename) will be called on first usage.
  132. ## Import/Export Analyzes
  133. Tools to quickly analyze ESM syntax and extract static `import`/`export`
  134. - Super fast Regex based implementation
  135. - Handle most edge cases
  136. - Find all static ESM imports
  137. - Find all dynamic ESM imports
  138. - Parse static import statement
  139. - Find all named, declared and default exports
  140. ### `findStaticImports`
  141. Find all static ESM imports.
  142. Example:
  143. ```js
  144. import { findStaticImports } from "mlly";
  145. console.log(
  146. findStaticImports(`
  147. // Empty line
  148. import foo, { bar /* foo */ } from 'baz'
  149. `),
  150. );
  151. ```
  152. Outputs:
  153. ```js
  154. [
  155. {
  156. type: "static",
  157. imports: "foo, { bar /* foo */ } ",
  158. specifier: "baz",
  159. code: "import foo, { bar /* foo */ } from 'baz'",
  160. start: 15,
  161. end: 55,
  162. },
  163. ];
  164. ```
  165. ### `parseStaticImport`
  166. Parse a dynamic ESM import statement previously matched by `findStaticImports`.
  167. Example:
  168. ```js
  169. import { findStaticImports, parseStaticImport } from "mlly";
  170. const [match0] = findStaticImports(`import baz, { x, y as z } from 'baz'`);
  171. console.log(parseStaticImport(match0));
  172. ```
  173. Outputs:
  174. ```js
  175. {
  176. type: 'static',
  177. imports: 'baz, { x, y as z } ',
  178. specifier: 'baz',
  179. code: "import baz, { x, y as z } from 'baz'",
  180. start: 0,
  181. end: 36,
  182. defaultImport: 'baz',
  183. namespacedImport: undefined,
  184. namedImports: { x: 'x', y: 'z' }
  185. }
  186. ```
  187. ### `findDynamicImports`
  188. Find all dynamic ESM imports.
  189. Example:
  190. ```js
  191. import { findDynamicImports } from "mlly";
  192. console.log(
  193. findDynamicImports(`
  194. const foo = await import('bar')
  195. `),
  196. );
  197. ```
  198. ### `findExports`
  199. ```js
  200. import { findExports } from "mlly";
  201. console.log(
  202. findExports(`
  203. export const foo = 'bar'
  204. export { bar, baz }
  205. export default something
  206. `),
  207. );
  208. ```
  209. Outputs:
  210. ```js
  211. [
  212. {
  213. type: "declaration",
  214. declaration: "const",
  215. name: "foo",
  216. code: "export const foo",
  217. start: 1,
  218. end: 17,
  219. },
  220. {
  221. type: "named",
  222. exports: " bar, baz ",
  223. code: "export { bar, baz }",
  224. start: 26,
  225. end: 45,
  226. names: ["bar", "baz"],
  227. },
  228. { type: "default", code: "export default ", start: 46, end: 61 },
  229. ];
  230. ```
  231. ### `findExportNames`
  232. Same as `findExports` but returns array of export names.
  233. ```js
  234. import { findExportNames } from "mlly";
  235. // [ "foo", "bar", "baz", "default" ]
  236. console.log(
  237. findExportNames(`
  238. export const foo = 'bar'
  239. export { bar, baz }
  240. export default something
  241. `),
  242. );
  243. ```
  244. ## `resolveModuleExportNames`
  245. Resolves module and reads its contents to extract possible export names using static analyzes.
  246. ```js
  247. import { resolveModuleExportNames } from "mlly";
  248. // ["basename", "dirname", ... ]
  249. console.log(await resolveModuleExportNames("mlly"));
  250. ```
  251. ## Evaluating Modules
  252. Set of utilities to evaluate ESM modules using `data:` imports
  253. - Automatic import rewrite to resolved path using static analyzes
  254. - Allow bypass ESM Cache
  255. - Stack-trace support
  256. - `.json` loader
  257. ### `evalModule`
  258. Transform and evaluates module code using dynamic imports.
  259. ```js
  260. import { evalModule } from "mlly";
  261. await evalModule(`console.log("Hello World!")`);
  262. await evalModule(
  263. `
  264. import { reverse } from './utils.mjs'
  265. console.log(reverse('!emosewa si sj'))
  266. `,
  267. { url: import.meta.url },
  268. );
  269. ```
  270. **Options:**
  271. - all `resolve` options
  272. - `url`: File URL
  273. ### `loadModule`
  274. Dynamically loads a module by evaluating source code.
  275. ```js
  276. import { loadModule } from "mlly";
  277. await loadModule("./hello.mjs", { url: import.meta.url });
  278. ```
  279. Options are same as `evalModule`.
  280. ### `transformModule`
  281. - Resolves all relative imports will be resolved
  282. - All usages of `import.meta.url` will be replaced with `url` or `from` option
  283. ```js
  284. import { transformModule } from "mlly";
  285. console.log(transformModule(`console.log(import.meta.url)`), {
  286. url: "test.mjs",
  287. });
  288. ```
  289. Options are same as `evalModule`.
  290. ## Other Utils
  291. ### `fileURLToPath`
  292. Similar to [url.fileURLToPath](https://nodejs.org/api/url.html#url_url_fileurltopath_url) but also converts windows backslash `\` to unix slash `/` and handles if input is already a path.
  293. ```js
  294. import { fileURLToPath } from "mlly";
  295. // /foo/bar.js
  296. console.log(fileURLToPath("file:///foo/bar.js"));
  297. // C:/path
  298. console.log(fileURLToPath("file:///C:/path/"));
  299. ```
  300. ### `pathToFileURL`
  301. Similar to [url.pathToFileURL](https://nodejs.org/api/url.html#urlpathtofileurlpath) but also handles `URL` input and returns a **string** with `file://` protocol.
  302. ```js
  303. import { pathToFileURL } from "mlly";
  304. // /foo/bar.js
  305. console.log(pathToFileURL("foo/bar.js"));
  306. // C:/path
  307. console.log(pathToFileURL("C:\\path"));
  308. ```
  309. ### `normalizeid`
  310. Ensures id has either of `node:`, `data:`, `http:`, `https:` or `file:` protocols.
  311. ```js
  312. import { ensureProtocol } from "mlly";
  313. // file:///foo/bar.js
  314. console.log(normalizeid("/foo/bar.js"));
  315. ```
  316. ### `loadURL`
  317. Read source contents of a URL. (currently only file protocol supported)
  318. ```js
  319. import { resolve, loadURL } from "mlly";
  320. const url = await resolve("./index.mjs", { url: import.meta.url });
  321. console.log(await loadURL(url));
  322. ```
  323. ### `toDataURL`
  324. Convert code to [`data:`](https://nodejs.org/api/esm.html#esm_data_imports) URL using base64 encoding.
  325. ```js
  326. import { toDataURL } from "mlly";
  327. console.log(
  328. toDataURL(`
  329. // This is an example
  330. console.log('Hello world')
  331. `),
  332. );
  333. ```
  334. ### `interopDefault`
  335. Return the default export of a module at the top-level, alongside any other named exports.
  336. ```js
  337. // Assuming the shape { default: { foo: 'bar' }, baz: 'qux' }
  338. import myModule from "my-module";
  339. // Returns { foo: 'bar', baz: 'qux' }
  340. console.log(interopDefault(myModule));
  341. ```
  342. **Options:**
  343. - `preferNamespace`: In case that `default` value exists but is not extendable (when is string for example), return input as-is (default is `false`, meaning `default`'s value is prefered even if cannot be extended)
  344. ### `sanitizeURIComponent`
  345. Replace reserved characters from a segment of URI to make it compatible with [rfc2396](https://datatracker.ietf.org/doc/html/rfc2396).
  346. ```js
  347. import { sanitizeURIComponent } from "mlly";
  348. // foo_bar
  349. console.log(sanitizeURIComponent(`foo:bar`));
  350. ```
  351. ### `sanitizeFilePath`
  352. Sanitize each path of a file name or path with `sanitizeURIComponent` for URI compatibility.
  353. ```js
  354. import { sanitizeFilePath } from "mlly";
  355. // C:/te_st/_...slug_.jsx'
  356. console.log(sanitizeFilePath("C:\\te#st\\[...slug].jsx"));
  357. ```
  358. ### `parseNodeModulePath`
  359. Parses an absolute file path in `node_modules` to three segments:
  360. - `dir`: Path to main directory of package
  361. - `name`: Package name
  362. - `subpath`: The optional package subpath
  363. It returns an empty object (with partial keys) if parsing fails.
  364. ```js
  365. import { parseNodeModulePath } from "mlly";
  366. // dir: "/src/a/node_modules/"
  367. // name: "lib"
  368. // subpath: "./dist/index.mjs"
  369. const { dir, name, subpath } = parseNodeModulePath(
  370. "/src/a/node_modules/lib/dist/index.mjs",
  371. );
  372. ```
  373. ### `lookupNodeModuleSubpath`
  374. Parses an absolute file path in `node_modules` and tries to reverse lookup (or guess) the original package exports subpath for it.
  375. ```js
  376. import { lookupNodeModuleSubpath } from "mlly";
  377. // subpath: "./utils"
  378. const subpath = lookupNodeModuleSubpath(
  379. "/src/a/node_modules/lib/dist/utils.mjs",
  380. );
  381. ```
  382. ## License
  383. [MIT](./LICENSE) - Made with 💛
  384. <!-- Badges -->
  385. [npm-version-src]: https://img.shields.io/npm/v/mlly?style=flat&colorA=18181B&colorB=F0DB4F
  386. [npm-version-href]: https://npmjs.com/package/mlly
  387. [npm-downloads-src]: https://img.shields.io/npm/dm/mlly?style=flat&colorA=18181B&colorB=F0DB4F
  388. [npm-downloads-href]: https://npmjs.com/package/mlly
  389. [codecov-src]: https://img.shields.io/codecov/c/gh/unjs/mlly/main?style=flat&colorA=18181B&colorB=F0DB4F
  390. [codecov-href]: https://codecov.io/gh/unjs/mlly