{"id":15374639,"url":"https://github.com/nktnet1/import-sync","last_synced_at":"2025-04-14T10:04:21.881Z","repository":{"id":200399637,"uuid":"705456334","full_name":"nktnet1/import-sync","owner":"nktnet1","description":"Synchronously and dynamically import ES6 modules in NodeJS","archived":false,"fork":false,"pushed_at":"2024-05-01T11:11:55.000Z","size":1078,"stargazers_count":12,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-05-02T06:04:30.337Z","etag":null,"topics":["cjs","commonjs","dynamic","es6","escmascript2015","esm","export","import","module","nodejs","require","runtime","sync","synchronous"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/import-sync","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nktnet1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-10-16T03:25:33.000Z","updated_at":"2024-05-10T00:33:25.846Z","dependencies_parsed_at":null,"dependency_job_id":"1718e44f-c1e0-40f0-bd8b-c3ed6aafd300","html_url":"https://github.com/nktnet1/import-sync","commit_stats":{"total_commits":96,"total_committers":4,"mean_commits":24.0,"dds":"0.44791666666666663","last_synced_commit":"fd82319ee073c5ad34e1fc86cba0ff30b028864f"},"previous_names":["nktnet1/import-sync"],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nktnet1%2Fimport-sync","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nktnet1%2Fimport-sync/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nktnet1%2Fimport-sync/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nktnet1%2Fimport-sync/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nktnet1","download_url":"https://codeload.github.com/nktnet1/import-sync/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":222515734,"owners_count":16996249,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cjs","commonjs","dynamic","es6","escmascript2015","esm","export","import","module","nodejs","require","runtime","sync","synchronous"],"created_at":"2024-10-01T13:59:14.070Z","updated_at":"2025-03-29T23:33:00.307Z","avatar_url":"https://github.com/nktnet1.png","language":"TypeScript","readme":"\u003cdiv align=\"center\"\u003e\n\n# [![Import Sync](logo.svg)](https://github.com/nktnet1/import-sync)\n\n[![pipeline](https://github.com/nktnet1/import-sync/actions/workflows/pipeline.yml/badge.svg)](https://github.com/nktnet1/import-sync/actions/workflows/pipeline.yml)\n\u0026nbsp;\n[![codecov](https://codecov.io/gh/nktnet1/import-sync/branch/main/graph/badge.svg?token=RAC7SKJTGU)](https://codecov.io/gh/nktnet1/import-sync)\n\u0026nbsp;\n[![Maintainability](https://api.codeclimate.com/v1/badges/aaae5cf33d58299ed722/maintainability)](https://codeclimate.com/github/nktnet1/import-sync/maintainability)\n\u0026nbsp;\n[![Snyk Security](https://snyk.io/test/github/nktnet1/import-sync/badge.svg)](https://snyk.io/test/github/nktnet1/import-sync)\n\u0026nbsp;\n[![GitHub top language](https://img.shields.io/github/languages/top/nktnet1/import-sync)](https://github.com/search?q=repo%3Anktnet1%2Fimport-sync++language%3ATypeScript\u0026type=code)\n\n[![NPM Version](https://img.shields.io/npm/v/import-sync?logo=npm)](https://www.npmjs.com/package/import-sync?activeTab=versions)\n\u0026nbsp;\n[![install size](https://packagephobia.com/badge?p=import-sync)](https://packagephobia.com/result?p=import-sync)\n\u0026nbsp;\n[![Depfu Dependencies](https://badges.depfu.com/badges/6c4074c4d23ad57ee2bfd9ff90456090/overview.svg)](https://depfu.com/github/nktnet1/import-sync?project_id=39032)\n\u0026nbsp;\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fnktnet1%2Fimport-sync.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fnktnet1%2Fimport-sync?ref=badge_shield)\n\u0026nbsp;\n[![NPM License](https://img.shields.io/npm/l/import-sync)](https://opensource.org/license/mit/)\n\u0026nbsp;\n[![GitHub issues](https://img.shields.io/github/issues/nktnet1/import-sync.svg?style=social)](https://github.com/nktnet1/import-sync/issues)\n\n[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=nktnet1_import-sync\u0026metric=alert_status)](https://sonarcloud.io/summary/new_code?id=nktnet1_import-sync)\n\u0026nbsp;\n[![Codacy Badge](https://app.codacy.com/project/badge/Grade/65161ae4d1c646ed83c9ef47b0a11473)](https://app.codacy.com/gh/nktnet1/import-sync/dashboard?utm_source=gh\u0026utm_medium=referral\u0026utm_content=\u0026utm_campaign=Badge_grade)\n\u0026nbsp;\n[![DeepSource](https://app.deepsource.com/gh/nktnet1/import-sync.svg/?label=active+issues\u0026show_trend=true\u0026token=r1frerF1-N2Mhrc7ZXIC1uNa)](https://app.deepsource.com/gh/nktnet1/import-sync/)\n\u0026nbsp;\n[![codebeat badge](https://codebeat.co/badges/acc44573-9938-4a14-bc41-7eb6a58dffbb)](https://codebeat.co/projects/github-com-nktnet1-import-sync-main)\n\u0026nbsp;\n[![GitHub stars](https://img.shields.io/github/stars/nktnet1/import-sync.svg?style=social)](https://github.com/nktnet1/import-sync/stargazers)\n\n[![Downloads Total](https://badgen.net/npm/dt/import-sync)](https://moiva.io/?npm=import-sync)\n\u0026nbsp;\n[![Downloads Yearly](https://badgen.net/npm/dy/import-sync)](https://moiva.io/?npm=import-sync)\n\u0026nbsp;\n[![Downloads Monthly](https://badgen.net/npm/dm/import-sync)](https://moiva.io/?npm=import-sync)\n\u0026nbsp;\n[![Downloads Weekly](https://badgen.net/npm/dw/import-sync)](https://moiva.io/?npm=import-sync)\n\u0026nbsp;\n[![Downloads Daily](https://badgen.net/npm/dd/import-sync)](https://moiva.io/?npm=import-sync)\n\n---\n\nSynchronously import dynamic ECMAScript Modules similar to CommonJS [require](https://nodejs.org/api/modules.html#requireid)\n\nBasic wrapper around [esm](https://github.com/standard-things/esm) for compatibility with both ESM and CJS projects in NodeJS\n\nCapable of importing ESM-only libraries such as [node-fetch@3](https://github.com/node-fetch/node-fetch#commonjs) in CJS projects\n\n[![Try with Replit](https://replit.com/badge?caption=Try%20with%20Replit)](https://replit.com/@nktnet1/import-sync-example#index.js)\n\n\u003c/div\u003e\n\n---\n\n- [1. Installation](#1-installation)\n- [2. Usage](#2-usage)\n    - [2.1. id](#21-id)\n    - [2.2. options](#22-options)\n    - [2.3. return](#23-return)\n- [3. License](#3-license)\n- [4. Limitations](#4-limitations)\n- [5. Caveats](#5-caveats)\n    - [5.1. Idea](#51-idea)\n    - [5.2. Discovery](#52-approach)\n    - [5.3. Result](#53-result)\n- [6. Major Changes](#6-major-changes)\n    - [6.1. 2023-12-16](#61-2023-12-16)\n\n## 1. Installation\n\n```\nnpm install import-sync\n```\n\n## 2. Usage\n\nTry with [Replit](https://replit.com/@nktnet1/import-sync-example#index.js).\n\n```\nimportSync(id, options);\n```\n\n\u003cdetails closed\u003e\n\u003csummary\u003eExamples (click to view)\u003c/summary\u003e\n\n\u003cbr/\u003e\n\nImporting from the same directory\n\n```javascript\nconst { someVariable, someFunction } = importSync('./some-module');\n```\n\nImporting `.mjs` file from a different directory\n\n```javascript\nconst { someFunction  } = importSync('../src/someModule.mjs');\n```\n\nUsing a different basePath\n\n```javascript\nconst { someFunction } = importSync(\n  './someModule',\n  { basePath: process.cwd() }\n);\n```\n\nUsing additional esm options as described in esm's [documentation](https://github.com/standard-things/esm#options)\n\n```javascript\nconst { someFunction } = importSync(\n  './someModule',\n  {\n    esmOptions: {\n      cjs: {\n        cache: true\n      },\n      mode: 'all',\n      force: true,\n    }\n  }\n);\n```\n\nImporting an ESM-only module\n\n```javascript\nconst fetch = importSync('node-fetch'),\n```\n\n\u003c/details\u003e\n\n\u003cbr/\u003e\n\n### 2.1. id\n\nModule name or relative path similar to CommonJS [require](https://nodejs.org/api/modules.html#requireid). For example,\n- `'../animals/cats.js'`\n- `'./dogs.mjs'`\n- `'./minimal'`\n    -  `importSync` will look for matching extensions in the order `[.js, .mjs, .cjs, .ts]`\n- `'node-fetch'`\n    - `importSync` can import pure-esm [node-fetch](https://github.com/node-fetch/node-fetch) (v3) into your cjs project\n\n### 2.2. options\n\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003cth\u003eOption\u003c/th\u003e\n    \u003cth\u003eDescription\u003c/th\u003e\n    \u003cth\u003eExample\u003c/th\u003e\n    \u003cth\u003eDefault\u003c/th\u003e\n  \u003c/tr\u003e\n\n  \u003ctr\u003e\n    \u003ctd\u003ebasePath\u003c/td\u003e\n    \u003ctd\u003e\n      This will only take effect if the given \u003ccode\u003eid\u003c/code\u003e starts with \u003ccode\u003e./\u003c/code\u003e or \u003ccode\u003e../\u003c/code\u003e.\n      \u003cbr/\u003e\n      For example,\n      \u003cul\u003e\n        \u003cli\u003e✅ \u003ccode\u003e./localLib\u003c/code\u003e\u003c/li\u003e\n        \u003cli\u003e✅ \u003ccode\u003e../src/localLib\u003c/code\u003e\u003c/li\u003e\n      \u003c/ul\u003e\n      and not\n      \u003cul\u003e\n        \u003cli\u003e❌ \u003ccode\u003e/home/user/localLib\u003c/code\u003e\u003c/li\u003e\n        \u003cli\u003e❌ \u003ccode\u003elocalLib.mjs\u003c/code\u003e\u003c/li\u003e\n        \u003cli\u003e❌ \u003ccode\u003enode-fetch\u003c/code\u003e\u003c/li\u003e\n      \u003c/ul\u003e\n      The ❌ examples above will be interpreted as either absolute paths or library imports.\n    \u003c/td\u003e\n    \u003ctd\u003e\n\u003cpre\u003e\n./myModule\n\u003c/pre\u003e\n    \u003c/td\u003e\n    \u003ctd\u003e\u003ccode\u003e__dirname\u003c/code\u003e\u003c/td\u003e\n\n  \u003ctr\u003e\n    \u003ctd\u003eesmOptions\u003c/td\u003e\n    \u003ctd\u003eOptions for the esm module as described in esm's \u003ca href=\"https://github.com/standard-things/esm#options\"\u003edocumentation\u003c/a\u003e.\u003c/td\u003e\n    \u003ctd\u003e\n\u003cpre\u003e\n{\n  cjs: true,\n  mode: 'auto'\n}\n\u003c/pre\u003e\n    \u003c/td\u003e\n    \u003ctd\u003e\u003ccode\u003eundefined\u003c/code\u003e\u003c/td\u003e\n  \u003c/tr\u003e\n\n\u003c/table\u003e\n\n### 2.3. return\n\nThe `importSync` function returns the exported module content similar to NodeJS\n[require](https://nodejs.org/api/modules.html#requireid).\n\nIf an unknown file path is provided a default\n[Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error)\nobject is thrown.\n\n## 3. License\n\n\u003cdetails closed\u003e\n\u003csummary\u003e\n  Massachusetts Institute of Technology\n  (\u003ca href=\"https://opensource.org/license/mit\" target=\"_blank\"\u003eMIT\u003c/a\u003e)\n\u003c/summary\u003e\n\n\u003cbr/\u003e\n\n```\nCopyright (c) 2023 Khiet Tam Nguyen\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the “Software”),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n```\n\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fnktnet1%2Fimport-sync.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fnktnet1%2Fimport-sync?ref=badge_large)\n\n\u003c/details\u003e\n\n## 4. Limitations\n\nThere are currently no known limitations.\n\n## 5. Caveats\n\n\u003e Please note that loading [ECMAScript Modules using require()](https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require) are soon to be supported in NodeJS natively.\n\n### 5.1. Idea\n\n**import-sync** was created to enable the implementation of a global dryrun script that can be run by students undertaking\n[COMP1531 Software Engineering Fundamentals](https://webcms3.cse.unsw.edu.au/COMP1531/23T2/outline) in their major group project. This requires the ability to import external ES Modules from any directory or path for use in both CommonJS and ESM-based projects.\n\nThe dryrun serves as a sanity check before the\nfinal submission is made, and is located in the centralised [COMP1531 course account](https://taggi.cse.unsw.edu.au/FAQ/Uploading_to_course_accounts/) at the path `~cs1531/bin`. Students who are connected to the CSE lab environment (e.g. via [VLAB](https://taggi.cse.unsw.edu.au/FAQ/VLAB_-_The_technical_details/)) can run the dryrun script from their major project repository, e.g. at the path `~z5313514/comp1531/project-backend`.\n\n### 5.2. Discovery\n\nInitially, the [esm](https://github.com/standard-things/esm) library looked promising. However, when the global dryrun script was executed in a mock student's project directory, the following error occurred:\n\n\u003e Error [ERR_REQUIRE_ESM]: require() of ES Module /import/ravel/5/z5313515/project-backend/src/auth.js not supported.\u003cbr/\u003e\nInstead change the require of auth.js in null to a dynamic import() which is available in all CommonJS modules\n\nThis is due to the `package.json` containing `\"type\": \"module\"`, as iteration 1 of the student major project uses ESM for the seamless transition to future iterations.\n\nThe following approaches were thus attempted, but were unsatisfactory for our purpose:\n\n1. [jewire](https://github.com/nktnet1/jewire)/[rewire](https://github.com/jhnns/rewire)/[require](https://nodejs.org/api/modules.html#requireid)\n    - in iteration 1, the dryrun requires the import of ES6 modules, so [jewire](https://github.com/nktnet1/jewire) (which was used for the dryrun of iteration 0) was no longer satisfying our requirements\n    - the same limitations of being CommonJS exclusive applies to [rewire](https://github.com/jhnns/rewire) and [require](https://nodejs.org/api/modules.html#requireid)\n2. [import()](https://nodejs.org/api/esm.html#import-expressions) - ECMAScript dynamic import\n    - this was the previous attempt at writing the dryrun\n    - However, it relied on asynchronous code. Since COMP1531 is **fully synchronous** (including the use of [sync-request-curl](https://github.com/nktnet1/sync-request-curl) for sending HTTP requests), this became a source of mystery and confusion for students\n    - additionally, students had to append the suffix `.js` to all of their file imports in the project solely to use the dryrun. This resulted in ambiguous error messages and obscure dryrun requirements unrelated to the project\n3. [require-esm-in-cjs](https://github.com/SamGoody/require-esm-in-cjs)\n    - this library utilises [deasync](https://github.com/abbr/deasync), which when used in NodeJS for Jest tests, could hang indefinitely as seen in Jest's issue [#9729](https://github.com/jestjs/jest/issues/9729)\n    - since COMP1531 uses Jest as the sole testing framework, [deasync](https://github.com/abbr/deasync) was ruled out\n4. Other async-to-sync conversions for dynamic [import()](https://nodejs.org/api/esm.html#import-expressions)\n    - [synckit](https://github.com/un-ts/synckit): worker_threads, Jest and external imports did not work (unclear reason)\n    - [sync-rpc](https://github.com/ForbesLindesay/sync-rpc): leaves orphan processes when used in Jest as explained in issue [#10](https://github.com/ForbesLindesay/sync-rpc/issues/10)\n    - [fibers](https://github.com/laverdet/node-fibers): obsolete and does not work for node versions later than 16\n    - [synchronize](https://github.com/al6x/synchronize): documentation link gives 404 and has fiber as a dependency\n    - [sync/node-sync](https://github.com/ybogdanov/node-sync): uses fiber (note: \"redblaze/node-sync\" on github, \"sync\" on npm)\n\n### 5.3. Result\n\nUpon a more thorough investigation into the initial issue with the\n[esm](https://github.com/standard-things/esm) module, the cause was the\nintroduction of the exception starting from NodeJS version 13, as noted in\n[@fregante](https://github.com/fregante)'s comment:\n- https://github.com/standard-things/esm/issues/855#issuecomment-558319872\n\nFurther down the thread was a link to the solution by [@guybedford](https://github.com/guybedford)\n- https://github.com/standard-things/esm/issues/868#issuecomment-594480715\n\nwhich removes the exception through module extension and serves as a satisfactory workaround. This reduced the codebase of **import-sync** to simply a wrapper around [esm](https://github.com/standard-things/esm).\n\nAnother issue that **import-sync** (v2) addresses is [esm's open issue #904](https://github.com/standard-things/esm/issues/904), which yields the error message:\n\u003e Error [ERR_INVALID_PROTOCOL]: Protocol 'node:' not supported. Expected 'file:'\n\nwhen importing ESM-only libraries such as [node-fetch@3](https://github.com/node-fetch/node-fetch/blob/8b3320d2a7c07bce4afc6b2bf6c3bbddda85b01f/README.md#commonjs) in a CommonJS module. This is done by overriding the default `Module._resolveFilename` function to remove the `node:` prefix, effectively changing any imports of the form (for example):\n```javascript\nimport http from 'node:http';\n```\nto\n```javascript\nimport http from 'http';\n```\nfor all imported modules.\n\nFor further discussions about this issue, visit:\n- https://stackoverflow.com/a/77329422/22324694\n\n---\n\n## 6. Major Changes\n\n### 6.1. 2023-12-16\n\nAs of version 2.2.0, **import-sync** has switched from using the archived [esm](https://github.com/standard-things/esm) package to the fork [@httptoolkit/esm](https://github.com/httptoolkit/esm). For further details, please see\n- issue [#37](https://github.com/nktnet1/import-sync/issues/37)\n- merge request [#38](https://github.com/nktnet1/import-sync/pull/38)\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnktnet1%2Fimport-sync","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnktnet1%2Fimport-sync","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnktnet1%2Fimport-sync/lists"}