1. Installation
npm install import-sync
2. Usage
Try with Replit.
importSync(relativePath, options);
Examples (click to view)
Importing from the same directory
const { someVariable, someFunction } = importSync('some-module');
Importing .mjs
file from a different directory
const { someFunction } = importSync('../src/someModule.mjs');
Using a different basePath
const { someFunction } = importSync(
'someModule',
{ basePath: process.cwd() }
);
Using additional esm options as described in esm's documentation
const { someFunction } = importSync(
'someModule',
{
esmOptions: {
cjs: {
cache: true
},
mode: 'all',
force: 'true',
}
}
);
2.1. relativePath
Path to the module relative to the current file, similar to CommonJS require. For example,
'../animals/cats.js'
'./dogs.mjs'
'minimal'
importSync
will look for './minimal.js'
before './minimal.mjs'
Note that option.basePath
can be provided to alter this behaviour.
2.2. options
Option | Description | Example | Default |
---|
basePath | Absolute path to the module. |
process.cwd()
| __dirname |
esmOptions | Options for the esm module as described in esm's documentation. |
{
cjs: true,
mode: 'auto'
}
| {} |
2.3. return
The importSync
function returns the exported module content similar to NodeJS
require.
If an unknown file path is provided a default
Error
object is thrown.
3. License
Massachusetts Institute of Technology
(MIT)
Copyright (c) 2023 Khiet Tam Nguyen
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fnktnet1%2Fimport-sync.svg?type=large)
4. Limitations
One known non-issue is that in jest, calling importSync
on
a CommonJS module returns an empty object.
There are currently no plans to fix this issue, as the built-in NodeJS
require function should simply be used
instead when importing CommonJS modules.
5. Caveats
5.1. Idea
import-sync was created to enable the implementation of a global dryrun
script that can be run by students undertaking
COMP1531 Software Engineering Fundamentals in their major group project. This requires the ability to import external ES6 modules from any directory or path for use in both CommonJS and ES6 programs.
The dryrun serves as a sanity check before the
final submission is made, and is located in the centralised COMP1531 course account at the path ~cs1531/bin
. Students who are connected to the CSE lab environment (e.g. via VLAB) can run the dryrun script from their major project repository, e.g. at the path ~z5313514/comp1531/project-backend
.
5.2. Discovery
Initially, the esm library looked promising. However, when the global dryrun script was executed in a mock student's project directory, the following error occurred:
Error [ERR_REQUIRE_ESM]: require() of ES Module /import/ravel/5/z5313515/project-backend/src/auth.js not supported.
Instead change the require of auth.js in null to a dynamic import() which is available in all CommonJS modules
This 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.
The following approaches were thus attempted, but were unsatisfactory for our purpose:
- jewire/rewire/require
- in iteration 1, the dryrun requires the import of ES6 modules, so jewire (which was used for the dryrun of iteration 0) was no longer satisfying our requirements
- the same limitations of being CommonJS exclusive applies to rewire and require
- import() - ECMAScript dynamic import
- this was the previous attempt at writing the dryrun
- However, it relied on asynchronous code. Since COMP1531 is fully synchronous (including the use of sync-request-curl for sending HTTP requests), this became a source of mystery and confusion for students
- 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
- require-esm-in-cjs
- this library utilises deasync, which when used in NodeJS for Jest tests, could hang indefinitely as seen in Jest's issue #9729
- since COMP1531 uses Jest as the sole testing framework, deasync was ruled out
- Other async-to-sync conversions for dynamic import()
- synckit: worker_threads, Jest and external imports did not work (unclear reason)
- sync-rpc: leaves orphan processes when used in Jest as explained in issue #10
- fibers: obsolete and does not work for node versions later than 16
- synchronize: documentation link gives 404 and has fiber as a dependency
- sync/node-sync: uses fiber (note: "redblaze/node-sync" on github, "sync" on npm)
5.3. Result
Upon a more thorough investigation into the initial issue with the
esm module, the cause was the
introduction of the exception starting from NodeJS version 13, as noted in
@fregante's comment:
Further down the thread was a link to the solution by @guybedford
which 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.