A simple module for better local requiring
npm i -S pquire
File structure:
<root>
┣╸lib
┃ ┣╸settings.js
┃ ┗╸util.js
┣╸src
┃ ┣╸module1.js
┃ ┣╸duplicate.js
┃ ┗╸mod2.js
┣╸duplicate.js
┗╸index.js
Function | Description |
---|---|
pquire(<path>) |
First tries to require relative to the current file, then, if that fails, requires relative to the package root. |
pquire.abs(<path>) |
Forces the require path to be relative to the root of the project. |
pquire.rel(<path>) |
Forces the require path to be relative to the path of the current file. This is the same as running require(./<path>) |
pquire.withBaseRelative(<path>) |
Creates a new pquire instance that uses <path> as its absolute base instead of getting it dynamically. This differs from withBaseAbsolute in that it interprets <path> relative to the current file. |
pquire.withBaseAbsolute(<path>) |
Creates a new pquire instance that uses <path> as its absolute base instead of getting it dynamically. This differs from withBaseRelative in that it interprets <path> relative to the project root. |
File structure:
<root>
┣╸lib
┃ ┣╸settings.js
┃ ┗╸util.js
┣╸src
┃ ┣╸module1.js
┃ ┣╸duplicate.js
┃ ┗╸mod2.js
┣╸duplicate.js
┗╸index.js
<root>/src/module1.js:
const pquire = require("pquire");
// Smart
const util = pquire("lib/util"); // <root>/lib/util.js
const dup1 = pquire("duplicate"); // <root>/src/duplicate.js
// Explicit
const mod2 = pquire.rel("mod2"); // <root>/src/mod2.js
const dup2 = pquire.abs("duplicate"); // <root>/duplicate.js
<root>/index.js:
// ...
global.pquire = require("pquire");
// ...
<root>/lib/util.js:
// No need to require pquire in this file.
const settings = pquire("settings"); // <root>/lib/settings.js
// ...
<root>
┗╸src
┣╸util
┃ ┗╸settings.js
┣╸sub
┃ ┗╸module1.js
┣╸mod2.js
┗╸index.js
<root>/src/index.js:
// ...
// Set the base path to '<root>/src'
global.pquire = require("pquire").withBaseRelative("./");
// ...
<root>/src/sub/module1.js:
// No need to require pquire in this file.
const settings = pquire("util/settings"); // <root>/src/util/settings.js
// ...