租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.0 KiB

3 months ago
  1. # ModuleImporter
  2. by [Nicholas C. Zakas](https://humanwhocodes.com)
  3. If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).
  4. ## Description
  5. A utility for seamlessly importing modules in Node.js regardless if they are CommonJS or ESM format. Under the hood, this uses `import()` and relies on Node.js's CommonJS compatibility to work correctly. This ensures that the correct locations and formats are used for CommonJS so you can call one method and not worry about any compatibility issues.
  6. The problem with the default `import()` is that it always resolves relative to the file location in which it is called. If you want to resolve from a different location, you need to jump through a few hoops to achieve that. This package makes it easy to both resolve and import modules from any directory.
  7. ## Usage
  8. ### Node.js
  9. Install using [npm][npm] or [yarn][yarn]:
  10. ```
  11. npm install @humanwhocodes/module-importer
  12. # or
  13. yarn add @humanwhocodes/module-importer
  14. ```
  15. Import into your Node.js project:
  16. ```js
  17. // CommonJS
  18. const { ModuleImporter } = require("@humanwhocodes/module-importer");
  19. // ESM
  20. import { ModuleImporter } from "@humanwhocodes/module-importer";
  21. ```
  22. ### Bun
  23. Install using this command:
  24. ```
  25. bun add @humanwhocodes/module-importer
  26. ```
  27. Import into your Bun project:
  28. ```js
  29. import { ModuleImporter } from "@humanwhocodes/module-importer";
  30. ```
  31. ## API
  32. After importing, create a new instance of `ModuleImporter` to start emitting events:
  33. ```js
  34. // cwd can be omitted to use process.cwd()
  35. const importer = new ModuleImporter(cwd);
  36. // you can resolve the location of any package
  37. const location = importer.resolve("./some-file.cjs");
  38. // you can also import directly
  39. const module = importer.import("./some-file.cjs");
  40. ```
  41. For both `resolve()` and `import()`, you can pass in package names and filenames.
  42. ## Developer Setup
  43. 1. Fork the repository
  44. 2. Clone your fork
  45. 3. Run `npm install` to setup dependencies
  46. 4. Run `npm test` to run tests
  47. ## License
  48. Apache 2.0
  49. [npm]: https://npmjs.com/
  50. [yarn]: https://yarnpkg.com/