Organized modules within an NPM package

I am looking to develop an NPM package that organizes imports into modules for better organization.

Currently, when I integrate my NPM package into other projects, the import statement looks like this:

import { myFunction1, myFunction2 } from 'my-package';

However, I would prefer to have the imports separated into modules like so:

import { myFunction1 } from 'my-package/products';
import { myFunction2 } from 'my-package/sales';

package.json

{
  "name": "my-package",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "rm -rf ./dist && tsc"
  },
  "devDependencies": {
    "typescript": "^5.2.2"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "incremental": true,
    "target": "es2020",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "commonjs",
    "baseUrl": "./src",
    "declaration": true,
    "outDir": "./dist",
    "removeComments": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "strictNullChecks": false,
    "skipLibCheck": true
  }
}

src/index.ts

export { myFunction1 } from './products';
export { myFunction2 } from './sales';

Your assistance is much appreciated. Thank you!

Answer №1

To achieve this functionality, you can utilize the "exports" entry in the package.json file:

"exports": {
  "./server": "./lib/server",
  "./react": "./lib/react"
},

Don't forget to include the corresponding declaration files as well.

react.d.ts

export * from "./lib/react";

server.d.ts

export * from "./lib/server";

For more detailed information on this topic, visit: https://nodejs.org/api/packages.html#packages_package_entry_points

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

Utilize IntelliJ's TypeScript/JavaScript feature to extract a method from all instances

I am relatively new to using IntelliJ Idea Ultimate 2020 and I am currently exploring the refactoring functionalities within the software. Is there a way to extract a method from a section of code and apply it to all instances easily and exclusively withi ...

Clicked but nothing happened - what's wrong with the function?

For my project, I have incorporated tabs from Angular Material. You can find more information about these tabs here. Below is the code snippet I am using: <mat-tab-group animationDuration="0ms" > <mat-tab></mat-tab> < ...

Determine the data type of a class property by referencing the data type of a different property within the

Why am I getting an error when assigning to this.propertyB in TypeScript? class Example { public readonly propertyA: boolean; private readonly propertyB: this['propertyA'] extends true ? null : 'value'; public constructor() ...

Trouble Calling Custom Module in Node.js

I've decided to give custom nodes a try and have found some code online that I'm testing out. Here is the code snippet I am currently working with: /** * mymodule.js Created by vinod on 4/13/2015. */ var exports = module.exports = {}; var myfu ...

Possible undefined object in React Redux

I'm encountering a Typescript issue where Redux object I am utilizing is potentially undefined, even though I have not specified its type as potentially being undefined or set it to be undefined anywhere in my code. /redux/globalSettings/actions.ts ...

What are some methods to troubleshoot $injector type errors in TypeScript?

I'm currently facing an issue with my AngularJS code. Here is a snippet of what I have: this.$injector.get('$state').current.name !== 'login' But, it's giving me the following error message: error TS2339: Property 'c ...

Tips for aligning the types of objects transmitted from a Web API backend to a React/Redux frontend

After creating a backend for my app using .net, I now have CRUD operations available to me. When performing a POST action, the response includes an entire new item object: {"Id":"7575c661-a40b-4161-b535-bd332edccc71","Text":"as","CreatedAt":"2018-09-13T15 ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Tips for displaying validation error messages in an Angular form

I need help displaying a validation error message for an Angular form. I have three checkboxes and I want to show an error message if none of them are selected. Can anyone provide guidance on how to implement reactive form validation in Angular? Here is a ...

Issue: "unable to locate the specified file or directory" error message encountered while attempting to include a GitLab private repository in the NPM package.json

Trying to include a GitLab private repository in another project's package.json. "dependencies": { "project": "git+https://myusername:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f99e908d95 ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

Sorry, I am unable to fulfill this request as it involves rewriting copyrighted content. However, I can provide some

Whenever I attempt to execute create-react-app myapp, I keep encountering an error. I have also attempted to clear the cache using npm cache clean --force Unfortunately, this did not resolve the issue. internal/modules/cjs/loader.js:638 throw err; ^ Er ...

React component's state is not being correctly refreshed on key events

Currently facing an issue that's puzzling me. While creating a Wordle replica, I've noticed that the state updates correctly on some occasions but not on others. I'm struggling to pinpoint the exact reason behind this discrepancy. Included ...

Retrieve every item in a JSON file based on a specific key and combine them into a fresh array

I have a JSON file containing contact information which I am retrieving using a service and the following function. My goal is to create a new array called 'contactList' that combines first names and last names from the contacts, adding an &apos ...

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...

Verify if a given string exists within a defined ENUM in typescript

I have an enum called "Languages" with different language codes such as nl, fr, en, and de. export enum Languages { nl = 1, fr = 2, en = 3, de = 4 } Additionally, I have a constant variable named "language" assigned the value 'de'. My g ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...

Issue encountered while executing the build command using npm run in a ReactJS project

Encountering an error when running "craco build" The command being executed is: npm run dist When I try to run npm run build from the same folder, I face the same error. Here are the commands in the package.json file: "scripts": { "start": "npm ru ...

What could be causing the "Failed to compile" error to occur following the execution of npm

Exploring react with typescript, I created this simple and basic component. import React, { useEffect, useState } from "react"; import "./App.css"; type AuthUser = { name: string; email: string; }; function App() { const [user, setUser] = useState& ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...