CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-import-from

Import a module like with require() but from a given path

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Import From

Import From provides a simple utility for importing Node.js modules from a specific directory path, similar to the built-in require() function but with the ability to specify the base directory for module resolution. It offers both a standard version that throws errors when modules can't be found and a silent version that returns undefined instead.

Package Information

  • Package Name: import-from
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install import-from

Core Imports

import importFrom = require('import-from');

CommonJS:

const importFrom = require('import-from');

Basic Usage

const importFrom = require('import-from');

// Import a module from a specific directory
try {
  const chalk = importFrom('./some-directory', 'chalk');
  console.log(chalk.blue('Hello world'));
} catch (error) {
  console.log('Module not found:', error.message);
}

// Silent import - returns undefined instead of throwing
const lodash = importFrom.silent('./some-directory', 'lodash');
if (lodash) {
  console.log(lodash.capitalize('hello'));
} else {
  console.log('Module not available');
}

Architecture

Import From uses Node.js's built-in createRequire API to create custom require functions that resolve modules from a specified directory. The core design pattern involves:

  • Path Resolution: Uses path.resolve() to convert the target directory into an absolute path
  • Require Function Creation: Creates a scoped require function using createRequire() with a dummy file path (noop.js) in the target directory
  • Module Resolution: The created require function resolves modules relative to the specified directory, following standard Node.js module resolution rules
  • Error Handling: Provides both throwing and silent versions for different error handling needs

This approach leverages Node.js's native module system while allowing custom resolution contexts, making it a lightweight wrapper around standard module loading behavior.

Capabilities

Module Import

Imports a module from a specified directory path, similar to require() but with custom base directory resolution.

/**
 * Import a module like with require() but from a given path
 * @param fromDirectory - Directory to import from
 * @param moduleId - What you would use in require()
 * @returns The imported module
 * @throws MODULE_NOT_FOUND error when the module can't be found
 */
function importFrom(fromDirectory: string, moduleId: string): unknown;

Usage Examples:

const importFrom = require('import-from');

// Import a relative module from a specific directory
const helper = importFrom('./src/utils', './helper');

// Import an npm package that's installed in a specific directory
const express = importFrom('./my-project', 'express');

// Import with path resolution
const config = importFrom('/absolute/path/to/project', './config.json');

Silent Module Import

Imports a module from a specified directory path, returning undefined instead of throwing when the module cannot be found.

/**
 * Import a module like with require() but from a given path
 * @param fromDirectory - Directory to import from
 * @param moduleId - What you would use in require()
 * @returns The imported module or undefined if not found
 */
importFrom.silent(fromDirectory: string, moduleId: string): unknown;

Usage Examples:

const importFrom = require('import-from');

// Safely attempt to import an optional dependency
const optionalDep = importFrom.silent('./plugins', 'optional-plugin');
if (optionalDep) {
  optionalDep.activate();
}

// Check for module availability without error handling
const devTool = importFrom.silent('./dev-tools', 'debug-helper');
const debugMode = !!devTool;

// Graceful fallback for missing modules
const preferredLib = importFrom.silent('./libs', 'preferred-lib') || 
                     importFrom.silent('./libs', 'fallback-lib');

Advanced Usage

Partial Application

Create a bound function for importing from the same directory multiple times:

const importFrom = require('import-from');

// Create a partial function for a specific directory
const importFromFoo = importFrom.bind(null, 'foo');

// Use the bound function multiple times
const bar = importFromFoo('./bar');
const baz = importFromFoo('./baz');

Error Handling

The standard importFrom function throws standard Node.js MODULE_NOT_FOUND errors:

const importFrom = require('import-from');

try {
  const missing = importFrom('./directory', './missing-module');
} catch (error) {
  console.log(error.code); // 'MODULE_NOT_FOUND'
  console.log(error.message); // "Cannot find module './missing-module'"
}

Implementation Details

  • Built on top of Node.js's createRequire API from the module module
  • Uses path.resolve() to handle directory path resolution
  • Creates a require function scoped to the specified directory
  • Requires Node.js >=12.2 (as specified in package.json)
  • No external dependencies - pure Node.js implementation

Types

declare const importFrom: {
  /**
   * Import a module like with require() but from a given path
   * @param fromDirectory - Directory to import from
   * @param moduleId - What you would use in require()
   * @throws Like require(), throws when the module can't be found
   */
  (fromDirectory: string, moduleId: string): unknown;

  /**
   * Import a module like with require() but from a given path
   * @param fromDirectory - Directory to import from
   * @param moduleId - What you would use in require()
   * @returns undefined instead of throwing when the module can't be found
   */
  silent(fromDirectory: string, moduleId: string): unknown;
};

export = importFrom;

docs

index.md

tile.json