This page looks best with JavaScript enabled

Refer Project Folder from NPM Package

 ·   ·  ☕ 1 min read

You can refer to other files/folders using a simple require or using basic node libraries. But, how can you do that with npm packages?

The Problem

When creating a bunch of Javascript files, here’s what you can do to refer other files -

1
const awe = require("../plugins/awesome.js");

This fetches awesome.js from the plugins folder in the parent.

You can do a more robust solution with -

1
const awe = require(path.join(__dirname, "../", "plugins"));

__dirname fetches the current directory, and you just join that with the path to reach to the file or folder.

But, what if you are packaging your app? __dirname refers to the packaged app folder, and is buried under node_modules as far as the consumer of the package is concerned.

The Solution

Use a reference to the main file to get path to the actual project folder.

1
2
const path = require("path");
console.log(path.dirname(require.main.filename));

The above line will print out the project folder rather than the package root folder within node_modules.

To refer plugins in project folder, you could do -

1
const awe = require(path.join(path.dirname(require.main.filename), "plugins"));

See require_main module for more information.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things