Search code examples
npmgitignorenpmignore

.npmignore: ignore whole folder except given file types


Background

I have a typescript project that I am publishing to npm. All my TS sources are in a folder called src and these are compiled to a folder called dist. src is likely to include some html templates, possibly css files and other assets. As part of the build these assets are all copied to the dist folder.

Source map files are also generated in the dist folder

When publishing I only really want to publish the dist folder but I want the source maps in the dist folder to work.

What I am trying to achieve

When I publish to npm I want to include the whole dist folder but ignore all non-ts files in the src folder.

The reason I need the .ts files is because the sourcemaps in the dist folder point to these source files. When debugging I need the original source to be able to see it in the browser.

So, I need to ignore src EXCEPT for the .ts files in src

What I have tried

I have tried the following which, based on my research, should work as far as I can tell.

# standard ignores

node_modules/
karma.conf.js
spec/

# ignore src

src/

# override above and include ts files

!src/**/*.ts
!src/**/*.d.ts

When I pack using this file I get the whole src folder in the package, including html, css and image files.

I was not sure if the above would work for a ts file directly under the src folder so I also tried

!src/actualFile.ts

but the result was the same.


Solution

  • Solution:

    Add the wildcards **/* to your ignore src pattern so it becomes:

    # ignore src
    
    src/**/*
    

    Additional comment:

    Your last negation pattern (i.e. !src/**/*.d.ts) can be omitted. It's effectively made redundant by its previous negation pattern (i.e. !src/**/*.ts).

    Using !src/**/*.ts alone will ensure any *.d.ts files in the src directory are also included.


    Complete revised .npmignore

    For clarity the complete revised .npmignore (given your example provided) should be:

    # standard ignores
    
    node_modules/
    karma.conf.js
    spec/
    
    # ignore src
    
    src/**/*
    
    # override above and include ts files
    
    !src/**/*.ts