Retrieve a specific subdirectory from the bundle

I've developed a Typescript package with the following file structure:

package.json
src/
  index.ts
  common/
    index.ts
  sub/
    index.ts

My goal is to import certain modules from the package like this:

import {...} from '<package>';
import {...} from '<package>/sub';

However, I do not want to allow importing from <package>/common.

Is there a way to achieve this without using custom declaration files?

The configuration in my package.json is inspired by this:

"exports": {
  ".": "./dist/index.js",
  "./common": "./dist/common/index.js"
},
"typesVersions": {
  "*": {
    "common": ["declarations/common/index.d.ts"]
  }
}

While this setup works fine for Typescript, I encounter an issue during the build process when attempting to access the module in JS:

Module not found: Error: Can't resolve '<package>/sub' in '...'

Answer №1

It's quite fascinating how this configuration in my package.json ended up solving the issue:

{
    // ...
    "files": [
        "/dist"
    ],
    "main": "./dist/index.js",
    "types": "./dist/index.d.ts",
    "exports": {
        ".": "./dist/index.js",
        "./types": "./dist/types/index.js",
        "./generate": "./dist/generate/index.js"
    },
    "typesVersions": {
        "*": {
            "types": [
                "./dist/types/index.d.ts"
            ],
            "generate": [
                "./dist/generate/index.d.ts"
            ]
        }
    }
}

This is what I have in my tsconfig.json:

{
    "extends": "@tsconfig/node14/tsconfig.json",
    "include": ["src/**/*"],
    "compilerOptions": {
        "lib": ["es2020", "dom"],
        "declaration": true,
        "outDir": "dist",
        "module": "ESNext"
    }
}

Here's a glimpse of my file setup:

package.json
tsconfig.json
dist/ // along with its subdirectories
src/
  generate/
    index.ts
  types/
    index.ts
  index.ts

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

The mystery of the undefined return value in my Ionic v4 get function

I attempted to retrieve my location by saving the latitude and longitude, but my declared variable isn't returning anything. Take a look at my code snippet: public device_location: any = {}; constructor(private geolocation: Geolocation) { this.s ...

encountering a problem with permissions while attempting to update npm

Has anyone encountered a permission error with npm when trying to update to the latest version? I recently tried updating npm and received this error message. I'm unsure of how to resolve it. Any suggestions? marshalls-MacBook-Air:Desktop marshall$ n ...

A TypeScript method for accessing deeply nested properties within an object

I'm currently working on a function that utilizes typings to extract values from a nested object. With the help of this post, I managed to set up the typing for two levels successfully. However, when I introduce a third (known) level between the exis ...

Troubleshooting offline pagination with dynamic MatTable containing matInputs (Angular 5 Material Design)

I have an issue with my component that contains an empty form with matInputs, as well as a mat-table with matInputs in the rows, all enclosed in mat-cards. The number of rows in the table is dynamic and based on another input called 'range'. So, ...

NestJs Function yielding inconsistent results based on its calling location

There is a puzzling issue that I am unable to solve. I have stored priceHistories in memory within an array. Strangely, when I invoke a get method, the returned value varies depending on where the method is called from. This is the original property and m ...

I am experiencing issues in the VS code terminal when attempting to execute an npm command

When attempting to use the npm command, an error is encountered stating that it is not recognized as a cmdlet, function, script file, or operable program. It is recommended to check the spelling of the command and ensure that the correct path is provided b ...

How to dynamically modify ion-list elements with Ionic on button click

Imagine having 3 different lists: List 1: bus, plane List 2: [related to bus] slow, can't fly List 3: [related to plane] fast, can fly In my Ionic Angular project, I have successfully implemented the first ion-list. How can I dynamically change th ...

`create-react-app: npm error! Unable to find a version that matches [email protected]``

I'm having trouble initializing a new react project using create-react-app: npx create-react-app . Unfortunately, I encountered an error: npm ERR! code ETARGET npm ERR! notarget No matching version found for <a href="/cdn-cgi/l/email-protection" c ...

How to retrieve the parent activated route in Angular 2

My route structure includes parent and child routes as shown below: { path: 'dashboard', children: [{ path: '', canActivate: [CanActivateAuthGuard], component: DashboardComponent }, { path: & ...

How should one go about publishing an npm package developed using Browserify in the package.json file?

I have a npm package that I developed using Browserify and I'm unsure about the correct way to structure the package.json. This package is a node server-client app (specifically an atom package), with the client side built on Browseriy. ./www/js/ind ...

Is it possible to safely remove a class instance containing a GLcontext within a react.FC State to prevent memory leaks, especially when using a "class object with THREE.js"?

I have successfully developed a react.FC() application. In this application, you have the ability to throw a bottle in the metaverse (like a message in a bottle) to be discovered in the future. The app retrieves information from an API and constructs a c ...

Generating dynamic content

I require assistance with a programming issue. I am working with two separate components: Stage and Executor. Within the Stage component, I am attempting to create new elements based on input parameters, while in the Executor component, I set these paramet ...

What is the best way to include the `bin/` folders within the `node_modules/` directory when adding files to T

I currently have a Build server running Team Foundation behind a firewall, and I'm looking to include the node_modules/ directory (which is utilized by both a Browserify client app and Node server app) in my project check-in. This will ensure that all ...

The Cypress-TinyMCE package consistently returns undefined for the editor instance when using TypeScript

My current project involves building a React JS application with TypeScript, where I utilize the TinyMCE editor within a form. To further enhance my development process, I am incorporating integration tests using Cypress in TypeScript. However, I have enco ...

Is there a possibility that NPM will restore dependencies that were published following the installation of the dependent package?

Let's assume that all references in the package.json file are at version ^1.0.0, and that only the patch version is being updated. In the scenario where A has a dependency on B, which in turn has a dependency on C: A > B > C. When I restore A a ...

Encountering a type error in Typescript when assigning a transition component to a Material UI Snackbar

Attempting to implement snackbar alert messages using Material UI in a React JS application with TypeScript. Encountering a type error when trying to modify the transition direction of the snackbar. Referenced the snackbar demo from Material UI documentat ...

The benefits of exporting a component from one module and using it in another module

After putting in long hours trying to figure this out on my own, I've finally decided to seek help from the community. Thank you in advance for any assistance! I have a Web Projects Module that utilizes a Webpage Component. Within the Webprojects Mod ...

Error: The variable <something> has not been defined

Within my GitHub project, an error stating Uncaught ReferenceError: breakpoints is not defined is appearing in the Chrome console. This issue should be resolved by including breakpoints.min.js, but it seems that webpack is somehow causing interference. I ...

Exploring the differences between initializing class members and using setters and getters in Typescript

Here is the code snippet that I am working with: export class Myclass { private _someVal = 2; public get someVal() { return this._someVal; } public set someVal(val) { this._someVal = val; } } In my template, I have <span&g ...

Contrasting "npm run dev" with "npm start"

I have just started learning about Node and AngularJS. Could someone explain the distinction between npm run dev and npm start commands in the node terminal? ...