No matter how hard I try, npm refuses to ignore my TypeScript source code file

I have a project that I developed using TypeScript and compiled to JavaScript before publishing it as a CLI tool through npm. However, I am facing an issue where the TypeScript source code is being included in the npm package, along with other random .ts files.

While I don't mind having the TypeScript files in the package, it adds unnecessary bytes for the end user who won't need them.

I have tried to exclude the TypeScript files using various methods, but they still end up in the package.

Here is a simplified setup:

{
    "name": "example",
    "version": "1.0.0",
    "main": "readme.js"
}

Despite trying to ignore all .ts files in the project using a .npmignore file, the readme.ts file still gets included.

To reproduce the issue, I created a few source code files:

touch readme.ts
touch readme.js

When generating the npm package, the readme.ts file is included, even though only readme.js is referenced in the package.json file.

I am puzzled as to why this is happening, since I have specifically excluded all .ts files and only specified readme.js in the package.json.

$ npm --version
6.13.1

Answer №1

Concise Response: When dealing with files named readme.* in npm, they will be included regardless of attempts to exclude them in your .npmignore file.


NPM Test File Overview:

One of npm's tests for the npm-cli known as "certain files included unconditionally" commences at line #511, and includes a scenario focused on a file named readme.randomext.

From the analysis of this test, it is evident that any file matching the pattern readme.* will be part of the tarball (.tgz) file despite specified exclusions in the .npmignore file.

Here is an excerpt from the aforementioned test suite entitled pack-files-and-ignores.js

test('certain files included unconditionally', function (t) {
  var fixture = new Tacks(
    Dir({
      'package.json': File({
        name: 'npm-test-files',
        version: '1.2.5'
      }),
      '.npmignore': File(
        'package.json',
        'README',
        'Readme',
        'readme.md',
        'readme.randomext',   // <----
        'changelog',
        'CHAngelog',
        'ChangeLOG.txt',
        'history',
        'HistorY',
        'HistorY.md',
        'license',
        'licence',
        'LICENSE',
        'LICENCE'
      ),
      'README': File(''),
      'Readme': File(''),
      'readme.md': File(''),
      'readme.randomext': File(''),     // <----
      'changelog': File(''),
      'CHAngelog': File(''),
      'ChangeLOG.txt': File(''),
      'history': File(''),
      'HistorY': File(''),
      'HistorY.md': File(''),
      'license': File(''),
      'licence': File(''),
      'LICENSE': File(''),
      'LICENCE': File('')
    })
  )
  withFixture(t, fixture, function (done) {
    t.ok(fileExists('package.json'), 'package.json included')
    t.ok(fileExists('README'), 'README included')
    t.ok(fileExists('Readme'), 'Readme included')
    t.ok(fileExists('readme.md'), 'readme.md included')
    t.ok(fileExists('readme.randomext'), 'readme.randomext included')    // <----
    t.ok(fileExists('changelog'), 'changelog included')
    t.ok(fileExists('CHAngelog'), 'CHAngelog included')
    t.ok(fileExists('ChangeLOG.txt'), 'ChangeLOG.txt included')
    t.ok(fileExists('license'), 'license included')
    t.ok(fileExists('licence'), 'licence included')
    t.ok(fileExists('LICENSE'), 'LICENSE included')
    t.ok(fileExists('LICENCE'), 'LICENCE included')
    done()
  })
})

Possible Solutions:

There are a couple of strategies that can be employed:

  1. The straightforward approach involves modifying the file name, for instance, to read-me.ts and then specifying read-me.ts in your .npmignore file. Given that you already have *.ts listed in your .npmignore, explicitly stating read-me.ts may not be necessary.

  2. If the renaming is not feasible, consider the following alternatives:

    • Incorporate a postpack script in the scripts section of your package.json. For example:

      "scripts": {
        "postpack": "node ./fix-it.js",
        ...
      },
      
    • Subsequently, in the file fix-it.js, utilize the node-tar package to:

      1. Extract the tarball (.tgz).
      2. Eliminate the undesired file(s) like readme.ts.
      3. Repackage to generate a new tarball (.tgz).
    • The progression for publishing your package would entail:

      1. Execute npm pack

        The postpack script will automatically produce the updated .tgz file without the specified file(s).

      2. Execute
        npm publish ./path/to/mypackage.tgz

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 npm-cache is packed with hundreds of pre-installed packages

After installing node.js and npm on my new Windows 7 machine via the msi installer, I discovered a cache of 150 packages in my users//appdata/roaming/npm-cache directory. How did they end up there? It doesn't seem like the msi installer did it. I&apo ...

The onChange function in CustomSelect is triggering an endless loop of renders in a React application using TypeScript and Material-

Currently, I am working with a mui element called CustomSelect. It functions perfectly on desktop, however, the handleChange function from onChange only console logs once. On mobile (even in development mode), it renders 51 times before crashing and displa ...

Configuring TypeScript for Firefox to recognize specific types such as browser.storage

As per the documentation from Mozilla, I should be able to utilize browser.storage.sync.get in my extension. However, I am encountering some challenges in getting TypeScript to recognize that I can use browser. I have attempted the following (which has wo ...

npm is unable to modify the version of the Jasmine package

Upon running npm view jasmine version or npm view jasmine version -g from the ~ directory, the returned version is 3.3.1 However, I require the version to be 2.8.0, so I attempted to downgrade using npm install <a href="/cdn-cgi/l/email-protection" cla ...

Error: The AppModule is missing a provider for the Function in the RouterModule, causing a NullInjectorError

https://i.stack.imgur.com/uKKKp.png Lately, I delved into the world of Angular and encountered a perplexing issue in my initial project. The problem arises when I attempt to run the application using ng serve.https://i.stack.imgur.com/H0hEL.png ...

Is it possible to determine the specific type of props being passed from a parent element in TypeScript?

Currently, I am working on a mobile app using TypeScript along with React Native. In order to maintain the scroll position of the previous screen, I have created a variable and used useRef() to manage the scroll functionality. I am facing an issue regardi ...

Encountering difficulties while attempting to deploy image on kubernetes due to issues with packaging structure

After successfully building with the dockerfile provided below, I encountered an issue when trying to deploy my application on EKS. FROM node:12 # Create app directory WORKDIR /usr/src/app COPY udagram-feed/package*.json ./ RUN npm ci # Bundle app sou ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: https://i.sstatic.net/jNiaO.png My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code s ...

What could be causing the error I encounter when attempting to send JSON in a GET request?

Currently, I am utilizing Angular 10 in my project. I am attempting to send an object in a GET request, so I decided to convert it to JSON: getData(dataPlan: Data): Observable<Response<InfoType[]>> { return this.client.get<Response< ...

The private package in the .npmrc file was overlooked

Currently, I am attempting to utilize my initial private npm package on a GitLab private instance. To my `.npmrc` file, I included @ajouve:registry=https://gitlab.my-website.io/api/v4/packages/npm/. Upon running the command npm get, it appears that the c ...

Exceed the capacity of a React component

Imagine having a React component that can render either a <button>, an <a>, or a React Router <Link> based on different props passed to it. Is it possible to overload this component in order to accept the correct props for each scenario? ...

Tips for accessing nested values post-subscription in Angular with JSON data?

I have implemented a getReports method that utilizes my web API's get method to retrieve JSON formatted responses. Step1 getReports() { return this._http.get(this.url) .map((response: Response) => response.json()) ...

Deciphering an ApplePay Token using JavaScript

Looking to decrypt an ApplePay token using NPM packages in JavaScript. Although there are repositories available for decrypting in Ruby like https://github.com/spreedly/gala, I am interested in porting it to JavaScript. However, I am uncertain about the Ja ...

Ways to prevent npm script from running automatically in the background

When working with npm scripts, I have a situation where some tasks need to run in parallel. My setup looks something like this: ... scripts: { "a": "taskA &", "preb": "npm run a", "b": "taskB" } ... Everything works well so far! But I am won ...

What are the downsides of utilizing a global function over a private static method in Typescript?

It's quite frustrating to have to write this.myMethod() or ClassName.myMethod() instead of just myMethod(). Especially when dealing with a stateless utility function that doesn't need direct access to fields. Take a look at this example: functi ...

The functionality of verifying the type of an item in a list using Typescript is not functioning

In my TypeScript code, I am working with a type called NameValue and another one called MixedStuff. type NameValue = { name: string; value: string }; type MixedStuff = NameValue | string; function stripTwoChars(stuffs: MixedStuff[]): string { let st ...

I recently updated all my projects to Angular 14, but when I tried to install a package using `npm i`, it still

The challenge at hand I encountered an issue with my two Angular projects. The first project serves as a library utilized by the second project. I recently upgraded both projects to Angular 14 following this guide. However, after running an npm i on the ...

I am facing an issue with the asynchronous function as it is displaying an error message

**I am facing an issue with displaying categories. I have attempted to do this using async function, however the data is not showing up** <div class="form-group"> <label for="category">Category</label> <select id="categor ...

The following error occurred in the css loader module: "ENOENT: The file or directory 'node_modules/node-sass/vendor' does not exist."

While attempting to run an Angular project on Windows 10, I encountered an error that I did not encounter when running the same project on Ubuntu. After cloning the repository and installing all the necessary node packages, the following error occurred: ...