index.js 1.4 KB

123456789101112131415161718192021222324
  1. 'use strict';
  2. const path = require('path');
  3. const {fileURLToPath} = require('url');
  4. const resolveCwd = require('resolve-cwd');
  5. const pkgDir = require('pkg-dir');
  6. module.exports = filename => {
  7. const normalizedFilename = filename.startsWith('file://') ? fileURLToPath(filename) : filename;
  8. const globalDir = pkgDir.sync(path.dirname(normalizedFilename));
  9. const relativePath = path.relative(globalDir, normalizedFilename);
  10. const pkg = require(path.join(globalDir, 'package.json'));
  11. const localFile = resolveCwd.silent(path.join(pkg.name, relativePath));
  12. const localNodeModules = path.join(process.cwd(), 'node_modules');
  13. const filenameInLocalNodeModules = !path.relative(localNodeModules, normalizedFilename).startsWith('..') &&
  14. // On Windows, if `localNodeModules` and `normalizedFilename` are on different partitions, `path.relative()` returns the value of `normalizedFilename`, resulting in `filenameInLocalNodeModules` incorrectly becoming `true`.
  15. path.parse(localNodeModules).root === path.parse(normalizedFilename).root;
  16. // Use `path.relative()` to detect local package installation,
  17. // because __filename's case is inconsistent on Windows
  18. // Can use `===` when targeting Node.js 8
  19. // See https://github.com/nodejs/node/issues/6624
  20. return !filenameInLocalNodeModules && localFile && path.relative(localFile, normalizedFilename) !== '' && require(localFile);
  21. };