NPM 是否忽略. gitignore 中列出的文件?

我有一个由 npm install命令(使用 preinstall任务)生成的文件。我不想将它添加到 git 存储库中,也不想添加到 NPM 项目中。

假设文件名是 foo.json,我将它作为 foo.json添加到 .gitignore文件中。

这是否足以避免将其上传到 NPM 注册表?

我知道我可以添加 .npmignore文件,肯定会忽略该文件,但我不会添加它,如果 .gitignore已经这样做。

34876 次浏览

If a project has both an .npmignore and .gitignore file, npm will only use the .npmignore file.

From the documentation:

Use a .npmignore file to keep stuff out of your package. If there's no .npmignore file, but there is a .gitignore file, then npm will ignore the stuff matched by the .gitignore file. If you want to include something that is excluded by your .gitignore file, you can create an empty .npmignore file to override it.

In simpler terms, npm prefers the .npmignore file if it is there, but will fall back to the .gitignore file.

In many cases, both Git and npm can ignore the same files, so it makes sense to just use a .gitignore file on its own. If there's ever a discrepancy (i.e. npm and Git need to ignore different files), then you need to maintain separate .gitignore and .npmignore files.

More information on what to put in .npmignore files: Should I .npmignore my tests?

For anyone reading this trying to ignore a file/dir from git but wish to include it in npm publish and have tried using an empty .npmignore file with no luck. This works.

In your .gitignore file, add the file/dir you wish to exclude **/build for example and in your .npmignore file make sure you specify the same file/dir but with the ! prefix so for the build example you would include !**/build