Miss any of our Open RFC calls?Watch the recordings here! »

root-import-utils

1.1.0 • Public • Published

root-import-utils

Functions for transforming import/require paths that have a prefix referring to the project root.

install

npm install root-import-utils

usage

const {
  hasPrefix,
  stripPrefix,
  getRelativePathToModule,
  getLongRelativePathToModule 
= require('root-import-utils')

API

hasPrefix(prefix, path)

hasPrefix('~', '~/a/b.js') // -> true
  • prefix: string
  • path: string
  • returns: boolean

stripPrefix(prefix, path)

stripPrefix('~', '~/a/b.js') // -> 'a/b.js'
  • prefix: string
  • path: string
  • returns: string the path argument with prefix removed. The / after the prefix is also removed so that the remaining path is relative.

getRelativePathToModule(sourcePathFromRoot, modulePathFromRoot)

getLongRelativePathToModule(sourcePathFromRoot, modulePathFromRoot)

  • sourcePathFromRoot: string relative path from project root to the file that has the import statement or require call
  • modulePathFromRoot: string the module path of import/require with prefix removed so that it is a relative path from project root

getLongRelativePathToModule() simply prepends the relative path from sourcePathFromRoot to the project root to modulePathFromRoot, rather than calculating the most direct path from source to the target module. That means it will return a more verbose path in some situations. See the following example.

getRelativePathToModule(    'a/b/c.js', 'a/b') // -> './'        // directly to module
getLongRelativePathToModule('a/b/c.js', 'a/b') // -> '../../a/b' // back to project root, forward to module

Install

npm i root-import-utils

DownloadsWeekly Downloads

18

Version

1.1.0

License

CC0-1.0

Last publish

Collaborators

  • avatar