How to include subdirectories in a TypeScript npm module

I am in the process of developing a package for npm and I would like it to be imported in the following manner:

import myPackage from 'my-package';
import { subFunction1, subFunction2 } from 'my-package/subfunctions';

Upon trying to utilize the package I have created, the main file loads without any issues but I encounter the following error when it comes to the subfolder:

Cannot find module 'my-package/subfunctions'

The current structure of the folder that is set to be published on npm is as follows:

index.js
index.d.ts
subfunctions/
  sub-function-1.js
  sub-function-1.d.ts
  sub-function-2.js
  sub-function-2.d.ts
  index.js
  index.d.ts

Furthermore, the type declarations in the package.json file are configured as:

"types": [
  "./dist/index.d.ts",
  "./dist/subfunctions/index.d.ts",
],

Below are the contents of the files index.d.ts (1) and subfunctions/index.d.ts (2):

(1)

import myCode from './lib/my-code';
export default myCode;

(2)

export { subFunction1 } from './sub-function-1';
export { subFunction2 } from './sub-function-2';

Is there a way for me to successfully import from this subfolder?

Answer №1

While this question may be old, I wanted to share a new answer that could be helpful. There is a recent addition to the package.json file called "exports" (introduced in Node.js 12+, around 2019) which serves as an alternative to "main" and could be exactly what you need if you're facing the same issue.

Although I haven't personally tested it, "exports" allows for "subpath exports", enabling you to export submodule code from a different location than your main:


{
  "main": "./index.js",
  "exports": {
    ".": "./index.js",
    "./subFunctions": "./src/subFunctions/index.js"
  }
}

Using this setup on the importing side will give you the desired outcome:

import myPackage from "my-package";
import subFunctions from "my-package/subFunctions";

Alternatively (this part is not explicitly clarified in the documentation, so I can't guarantee it, but it seems logical):

import myPackage from "my-package";
import { subFunction1, subFunction2 } from "my-package/subFunctions";

...assuming that src/subFunctions/index.js has corresponding named exports.

If this information is inaccurate, I apologize as I'm merely relaying what I found in the documentation (discovered coincidentally a few days after stumbling upon this question). Hopefully, this can be useful to someone.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered during creation of a polyline in Cesium

When attempting to create a polyline in my ReactJs app using the code below, I encountered an error message stating "DeveloperError: Expected value to be greater than or equal to 0.0125, the actual value was 0." Can someone shed some light on why this er ...

Can you explain the distinction between these two npm installation commands?

To install @uiw/react-monacoeditor using npm, you can use either the command <strong>npm install @uiw/react-monacoeditor --save</strong> or simply <strong>npm i @uiw/react-monacoeditor</strong>. But what exactly is the difference ...

The user's input is not being bound properly when using $scope.$watch

Just started my Angular journey and I've been stuck for the past couple of days trying to figure out how to bind data from a new search using a service. Previously, I had the search functionality working with the code below before transitioning to a s ...

How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially ...

Is it possible in Vuetify 2 to align the items within the expansion of a v-data-table with the headers of the main component?

I am currently working on rendering a v-data-table where the expandable section serves as a "panel" title and I want the data inside the expansion to align with the headers set at the root level. Despite my efforts, I have not been able to find a way in th ...

When working with JavaScript, it's important to note that any reference used outside of the catch block

Our JavaScript code includes a try...catch block that functions as follows: We import the customFile using: const ourCustomClassFile = require('./customFile'); In the customFile.js file, we have defined a function const sendErrorNotification ...

I'm having trouble resolving the issue in my React App after attempting to export a functional component. How can I troubleshoot and

Since the first week of this online course on Coursera.org, I've been struggling to get my React app to display. Even after watching videos and revising the code multiple times based on Google search results, I couldn't make it work. Despite seek ...

Using JavaScript Object Constructor to alter text color

Seeking some guidance as a newbie here on how to deal with a problem I'm currently tackling. I understand that using an object constructor may not be the most efficient way to handle this, but I'm eager to enhance my knowledge of objects. My quer ...

The child component is receiving null input data from the Angular async pipe, despite the fact that the data is not null in the

I encountered a strange scenario that I'm unable to navigate through and understand how it occurred. So, I created a parent component called SiteComponent. Below is the TypeScript logic: ngOnInit(): void { this.subs.push( this.route.data.subscribe( ...

JavaScript: Working with Nested Callbacks and Retrieving MySQL Data

As I dive into the world of JavaScript server-side code, I find myself grappling with a common issue that many programmers face. In my previous experience with MySQL select queries in PHP, I would simply grab a result and loop through each row, performing ...

When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active. I could really use some help with this as it's starting to get on my nerves ...

Tips for storing dynamic data in an array using JavaScript

I'm trying to create a loop that will retrieve the href values from certain elements and store them in an array. Can someone help me with this? var linksArray = []; var elements = document.getElementsByClassName("title"); for (var i = 0; i < elem ...

Can someone please point me in the right direction to locate a Typescript project within Visual Studio

I've been struggling with this issue for days and still can't find a solution. After installing the Typescript tool for Visual Studio 2015, it appears to be successfully installed. https://i.stack.imgur.com/nlcyC.jpg However, I am unable to loc ...

Setting values to an array based on the index of a specific name in JavaScript - a guide

How can I set values to an array if it has an index in the name field? Here is the sample data: [ { "column": "created_at[0]", "name": "created_at[0]", "type": "range", ...

Is there a way to modify the CSS or add custom styling within an iframe form?

Currently I am working on the following page: , where an embedded javascript form called infusionsoft (iframe form) needs to be made responsive at the request of my client. I'm wondering if there is a way to override the css or inject custom styles i ...

Adjust the image dimensions within the DIV container

I am currently working on creating my personal portfolio website. I have encountered an issue where the image inside a div element enlarges the size of the entire div as well. My goal is to keep the image slightly larger while maintaining the same size for ...

Unable to execute simple demo on the threejs.org platform

As I delve into learning three.js, I came across some examples worth exploring. One specific code snippet I attempted to execute can be found here. Unfortunately, all I saw was a blank black screen. To troubleshoot, I adjusted the three.js source to my lo ...

Unveiling the Secrets of Unearthing Data from JSON

My code receives JSON strings through a JSONP call. Although I'm aware of the general JSON structure, I don't know the specific keys and values it will contain. The typical structure is as follows: [ {"key_name": "value"}, {"key_name": ...

Leverage the Express JS .all() function to identify the specific HTTP method that was utilized

My next task involves creating an endpoint at /api that will blindly proxy requests and responses to a legacy RESTful API system built in Ruby and hosted on a different domain. This is just a temporary step to transition smoothly, so it needs to work seam ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...