What is the importance of including `src` in the import statement when publishing a package?

I am currently in the process of learning how to publish a typescript package on NPM. The package I am working on is quite simple at this point, as it mainly just exports some random number functions. However, I have plans for it to do much more in the future:

src
  /random
    /index.ts
  /index.ts
package.json
tsconfig.json
.gitignore

When attempting to import the npm package into another typescript project, an error arises:

import {Random} from "@whiterook6/my-package";

console.log(Random.randomInt(1, 10));
Cannot find module '@whiterook6/my-package' or its corresponding type declarations.ts(2307)

However, adjusting the import statement like so resolves the issue:

import {Random} from "@whiterook6/my-package/src";

console.log(Random.randomInt(1, 10));

I am puzzled as to what I might have done incorrectly within my library package to lead to this undesirable outcome, and I am seeking guidance on how to modify it so that users can utilize these types of imports:

import {Random, Logger} from "@whiterook6/my-package";

Below is the content of my tsconfig.json file:

{
  "compilerOptions": {
    "target": "ESNext", // Specify the ECMAScript target version
    "module": "ESNext", // Specify the module code generation
    "moduleResolution": "node", // Specify module resolution strategy
    "declaration": true, // Generate declaration files
    "emitDeclarationOnly": true, // Only emit declaration files
    "outDir": "./src", // Redirect output structure to the directory
    "rootDir": "./src", // Specify the root directory of input files
    "strict": true, // Enable strict type checking options
    "esModuleInterop": true, // Enable compatibility with CommonJS and ES modules
    "skipLibCheck": true, // Skip type checking of declaration files
    "forceConsistentCasingInFileNames": true // Ensure consistent casing in imports
  },
  "include": [
    "src/**/*" // Include all files in the src directory
  ],
  "exclude": [
    "node_modules", // Exclude node_modules directory
    "dist" // Exclude dist directory
  ]
}

Answer №1

By changing the import statement to [

import {Random} from "@whiterook6/my-package/src";
], it successfully works

This indicates that your package.json file does not define "exports" (which would prevent importing files from your package), or a correct "main" entry point.

You can specify what gets returned when a consumer project imports the root of your package using the "main" field:

For example, if your package is named foo, and a user installs it, then calls require("foo"), the main module's exports will be returned.

In your situation, you could do the following in your package.json:

// package.json
{
  "main": "src/index"
}

Alternatively, you can use the "exports" field as recommended in Tim Hansen's answer:

// package.json
{
  "exports": {
    ".": "src/index"
  }
}

Answer №2

To configure the exports in your package.json, you will need to follow these steps:

Below is an example of how this should be set up:

package.json

exports: {
    "./specificModule": "./dist/specificModule/index.js"
}

For further assistance, refer to this link:

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

Produce new lines of code using the vscode.window.activeTextEditor.edit method in Visual Studio Code

Hey everyone, I'm currently working on a vscode extension that can automatically generate template code based on the language you are using when you click a button. However, there seems to be an issue with the formatting of the generated code as it do ...

Angular: Why Do Styles Fail to be Applied to Dynamically Inserted HTML Elements?

I am having trouble applying styles to a newly added "i" element as a child element to an HTMLDivElement. The styles set in the scss file are not being applied to the new element. Is there a way to ensure that the same styles are applied to the newly adde ...

Getting the PlayerId after a user subscribes in OneSignal with Ionic2

Currently working on an app with Ionic2 and facing a challenge with retrieving the player id after a user subscribes in order to store it in my database. Any suggestions on how I can retrieve the unique player id of OneSignal users post-subscription? ...

Typescript type for selecting only string[] keys in an object

I am looking for a specific type: interface Filter<P extends object> { label: string; options: FilterOption[]; key: StringArrayKeyOf<P>; } The definition of StringArrayKeyOf is as follows: type StringArrayKeyOf<T extends object> = ...

The term 'string' is typically employed as a data type, yet in this instance it is being utilized as an actual value

Just started working with TypeScript and encountered an issue while trying to set the state. Encountered this error message: 'string' is a type and cannot be used as a value here. const state = reactive({ user: { uid: "", ...

It is frustrating how much time it takes to install an npm package after a sudden computer shutdown

While I was in the process of installing Expo through the command prompt, my computer unexpectedly shut down because of a battery issue. Now that I am trying to resume the installation, it appears to be stuck where it left off before the shutdown. What s ...

Node installation of electron on windows appears to hang

Currently, I am working through the quick installation guide for Electron found at Here is the script I am following: Step 1: Clone the Quick Start repository git clone https://github.com/electron/electron-quick-start Step 2: Navigate to the repository ...

The exclude option in Nest JS middleware does not prevent the middleware from running on excluded routes

I'm having an issue with excluding certain routes from the middleware. The .exclude option doesn't seem to be working as expected, as the middleware is still being applied to the excluded routes. Here is the code for the Middleware: https://i.st ...

Using TypeScript generics to create reusable type definitions for reducers

I have a common reducer function that needs to be properly typed. Here's what I have come up with: export interface WithInvalidRows<T extends { [K in keyof T]: InvalidCell[] }> { invalidRows: T; } interface AddPayload<S extends WithInval ...

Understanding the return parameter "typeof SomeClass" in TypeScript

typeof in JavaScript returns a string. The TypeScript typings for Sequelize include return types of typeof Model. What does this mean and what is its purpose? I have looked through the documentation but could not find an explanation. Link to Sequelize Typ ...

Steps to globally modify the font in Ionic

In my Ionic app running version 3.9.2, I am attempting to customize the default font to a specific custom one. After researching, I discovered that I need to set the font face in the app.scss file located within the app folder. Here is the code snippet I ...

Issues arise during Angular2 building process, such as failure to locate the name 'document' and unresolved references

Recently, I've been incorporating Jasmine unit tests into my Angular 2 project and made updates to some NPM packages. As a result, I've encountered two distinct errors that seem to be interconnected, so I thought it best to address both in one qu ...

Analyze two sets of JSON data and compile a new JSON containing only the shared values

I am trying to generate two JSON arrays based on a shared property value from comparing two sets of JSON data. this.linkedParticipants =[ { "id": 3, "name": "Participant 2", "email": "<a href="/ ...

Testing Angular components with Jest's mocking capabilities

I've been grappling for a while now with trying to simulate a specific function that I need to test. Despite going through the Jest documentation, I haven't been able to piece together the solution. I couldn't find any relevant questions tha ...

Is there a way to execute a secondary npm script when the primary script fails to run?

One of the key npm scripts in my arsenal is "npm run build". I am looking to create an additional script that acts as a safety net, kicking in whenever "npm run build" encounters an error. ...

PhpStorm IDE does not recognize Cypress custom commands, although they function properly in the test runner

Utilizing JavaScript files within our Cypress testing is a common practice. Within the commands.js file, I have developed a custom command: Cypress.Commands.add('selectDropdown', (dropdown) => { cy.get('#' + dropdown).click(); } ...

Jenkins script ending abruptly while attempting to run npm install on a Windows machine

When setting up my Jenkins job, I encountered an issue with building a JavaScript app using Grunt. The Jenkins build scripts are supposed to create a build directory (if it doesn't exist), navigate to that directory, and execute the following commands ...

What is the process for defining the type or interface of an object in Visual Studio Code?

Is there a way to create a new type or interface by replicating the structure of a complex object that is imported from a library? For instance, in the image below, the object Text is taken from react-three/drei. https://i.sstatic.net/BcUzd.png Upon inspe ...

The error message displayed is "Unable to locate module."

After recently upgrading to node version 9.0.0, I encountered an error in the command line while attempting to use npm install. npm ERR! code MODULE_NOT_FOUND npm ERR! Cannot find module 'internal/util/types' My system details are: Operating ...

What is the reason for having both the Video.js npm module and the <script> tag in place?

After referring to the official Video.js documentation at , it is recommended to add script tags for both js and css to your webpage. Additionally, you can install the package manager through npm or bower. What is the purpose of utilizing both approaches? ...