Let a globally installed package use a locally installed version of itself if available
npx @tessl/cli install tessl/npm-import-local@3.2.0Let a globally installed package use a locally installed version of itself if available. Useful for CLI tools that want to defer to the user's locally installed version when available, but still work if it's not installed locally.
npm install import-localconst importLocal = require('import-local');For ES Modules:
import importLocal from 'import-local';For TypeScript:
import importLocal from 'import-local';const importLocal = require('import-local');
if (importLocal(__filename)) {
console.log('Using local version of this package');
} else {
// Code for both global and local version here…
}For ES Modules:
import importLocal from 'import-local';
if (importLocal(import.meta.url)) {
console.log('Using local version of this package');
} else {
// Code for both global and local version here…
}Detects if a locally installed version of the current package is available and imports it if found.
/**
* Let a globally installed package use a locally installed version of itself if available
* @param filePath - The absolute file path to the main file of the package (supports __filename for CommonJS or import.meta.url for ES modules)
* @returns The required local module if found, otherwise false
*/
function importLocal(filePath: string): any | false;Parameters:
filePath (string): The absolute file path to the main file of the package. Can be:
__filename when used in CommonJS contextimport.meta.url when used in ES modules contextReturn Value:
false if no local version is available or if the current execution is already from a local installationBehavior:
__filename) and ES modules (import.meta.url) contextsUsage Examples:
CommonJS CLI tool:
#!/usr/bin/env node
const importLocal = require('import-local');
if (importLocal(__filename)) {
// Local version will handle execution
process.exit(0);
}
// Global version code continues here
console.log('Running global version');ES Modules entry point:
import importLocal from 'import-local';
if (importLocal(import.meta.url)) {
// Local version will handle execution
process.exit(0);
}
// Global version code continues here
console.log('Running global version');Package main file:
const importLocal = require('import-local');
const path = require('path');
// Check for local version using explicit path
const localModule = importLocal(path.join(__dirname, 'index.js'));
if (localModule) {
module.exports = localModule;
} else {
// Export global version functionality
module.exports = require('./lib/global-implementation');
}