Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

tsimportlib

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

tsimportlib

> Currently an alpha-quality, best-effort implementation. > May be unnecessary if you use TypeScript's `"module": "NodeNext", "moduleResolution": "NodeNext"`

  • 0.0.5
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
13K
decreased by-13.4%
Maintainers
1
Weekly downloads
 
Created
Source

Dynamic import within TS compiled to CommonJS

Currently an alpha-quality, best-effort implementation.
May be unnecessary if you use TypeScript's "module": "NodeNext", "moduleResolution": "NodeNext"

Node.js allows dynamic import() calls within CommonJS file. TypeScript transforms import() into require() when targetting CommonJS.

This presents a problem when a .ts file compiled to CommonJS wants to do a truly async, dynamic import of a native ESM module. How do we avoid TypeScript's transformation from import() to require()?

This library implements a workaround. Replace import('lib') with dynamicImport('lib', module).

import {dynamicImport} from 'tsimportlib';

async function main() {
    const dynamicallyImportedEsmModule = await dynamicImport('truly-esm-module', module) as typeof import('truly-esm-module');
}

async function loadPlugin(name: string) {
    // In this example, plugins may or may not be native ESM, so we use dynamic import to support both.
    const dynamicallyImportedPlugin = await dynamicImport(name, module) as MyPluginInterface;
}

Limitations

Due to Node.js limitations, we must use the CommonJS resolver to locate modules. This should work well enough for third-party modules, but may not work for dual-mode modules or ones that suppress importing of their package.json file. As a fallback you can pass an absolute path to the target module.

Keywords

FAQs

Package last updated on 16 May 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc