What is import-from?
The npm package 'import-from' allows you to import modules from a specific path, bypassing the default behavior of Node.js module resolution. This can be particularly useful in scenarios where you need to dynamically choose different versions of a module or when working with plugins that may not be in the node_modules directory of the current project.
What are import-from's main functionalities?
Import module from a specific directory
This feature allows you to import a module by specifying the directory from which the module should be loaded. This is useful for loading modules dynamically based on runtime conditions or configurations.
const importFrom = require('import-from');
const specificModule = importFrom('/path/to/specific/directory', 'module-name');
Silent import attempt
This feature provides a way to attempt to import a module silently without throwing errors if the module does not exist. It is useful for optional dependencies that may or may not be present in a given environment.
const importFrom = require('import-from');
const tryImport = importFrom.silent('/path/to/directory', 'optional-module');
Other packages similar to import-from
require-from-string
This package allows you to require modules from a string of code. It is similar to 'import-from' in that it modifies the standard module loading behavior, but it focuses on executing and importing code from strings rather than from specific file paths.
proxyquire
Proxyquire is designed to help with mocking dependencies for testing purposes. It allows you to replace modules in require calls within the module under test. While it also changes how modules are loaded, it is specifically tailored for testing rather than general module loading from different locations.
import-from
Import a module like with require()
but from a given path
Install
$ npm install import-from
Usage
const importFrom = require('import-from');
importFrom('foo', './bar');
API
importFrom(fromDirectory, moduleId)
Like require()
, throws when the module can't be found.
importFrom.silent(fromDirectory, moduleId)
Returns undefined
instead of throwing when the module can't be found.
fromDirectory
Type: string
Directory to import from.
moduleId
Type: string
What you would use in require()
.
Tip
Create a partial using a bound function if you want to import from the same fromDir
multiple times:
const importFromFoo = importFrom.bind(null, 'foo');
importFromFoo('./bar');
importFromFoo('./baz');
Related
- import-cwd - Import a module from the current working directory
- resolve-from - Resolve the path of a module from a given path
- resolve-cwd - Resolve the path of a module from the current working directory
- resolve-pkg - Resolve the path of a package regardless of it having an entry point
- import-lazy - Import modules lazily
- import-global - Import a globally installed module