乐趣区

npmignoregitignore和packagejson中的files字段

本文参考了这篇文章 https://docs.npmjs.com/misc/developers;
问题场景:npm publish 发布一个 npm 包,发布的时候你希望只发布打包的文件,包的源码,单元测试等文件不希望发布;
.npmignore 中的文件不会被发布,默认情况下,npm publish 发布目录中的所有文件,除了

  • .*.swp
  • ._*
  • .DS_Store
  • .git
  • .hg
  • .npmrc
  • .lock-wscript
  • .svn
  • .wafpickle-*
  • config.gypi
  • CVS
  • npm-debug.log

所以不需要把这些文件加入到.npmignore 中也会忽略,如果没有.npmignore, 有.gitignore,那么.gitignore 中的文件会从包中忽略,如果同时存在,那么.npmignore 的优先级更好,体会一下:
If you want to include something that is excluded by your .gitignore file, you can create an empty .npmignore file to override it. Like git

并且.gitignore 和.npmignore 中的文件是递归查找的,再体会一下:
npm looks for .npmignore and .gitignore files in all subdirectories of your package, not only the root directory.

这些是默认发布的文件,加入.gitignore 和.npmignore 都是不会生效的:

  • package.json
  • README(and its variants)
  • CHANGELOG(and its variants)
  • LICENSE/LICENCE

所以当你 npm publish 的时候,为啥总会有 package.json 文件,明白了吧?这几个文件在 npm publish 的时候都是默认作为包的一部分的

介绍下 package.json 中的 files 字段,这个字段中的文件默认不会加入到 npm publish 发布的包中,它的优先级高于.npmignore 和.gitignore,这个才是使用最广的方法,好像很多开源项目用的都是 files 字段

退出移动版