版博士V2.0程序
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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