How to publish an npm package with distribution files? How to publish an npm package with distribution files? git git

How to publish an npm package with distribution files?


When you npm publish, if you don't have an .npmignore file, npm will use your .gitignore file (in your case you excluded the dist folder).

To solve your problem, create a .npmignore file based on your .gitignore file, without ignoring the dist folder.

Soure : https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package


Take a look at the "files" field of package.json filehttps://docs.npmjs.com/files/package.json#files

From the documentation:

The "files" field is an array of files to include in your project. If you name a folder in the array, then it will also include the files inside that folder. (Unless they would be ignored by another rule.)


Minimal example of how to use data files from a script

Another common use case is to have data files that your scripts need to use.

This can be done easily by using the techniques mentioned at: In node.JS how can I get the path of a module I have loaded via require that is *not* mine (i.e. in some node_module)

The full example can be found at:

With this setup, the file mydata.txt gets put into node_modules/cirosantilli-data-files/mydata.txt after installation because we added it to our files: entry of package.json.

Our function myfunc can then find that file and use its contents by using require.resolve. It also just works on the executable ./cirosantilli-data-files of course.

package.json

{  "bin": {    "cirosantilli-data-files": "cirosantilli-data-files"  },  "license": "MIT",  "files":  [    "cirosantilli-data-files",    "mydata.txt",    "index.js"  ],  "name": "cirosantilli-data-files",  "repository": "cirosantilli/linux-kernel-module-cheat",  "version": "0.1.0"}

mydata.txt

hello world

index.js

const fs = require('fs');const path = require('path');function myfunc() {  const package_path = path.dirname(require.resolve(    path.join('cirosantilli-data-files', 'package.json')));  return fs.readFileSync(path.join(package_path, 'mydata.txt'), 'utf-8');}exports.myfunc = myfunc;

cirosantilli-data-files

#!/usr/bin/env nodeconst cirosantilli_data_files = require('cirosantilli-data-files');console.log(cirosantilli_data_files.myfunc());

The is-installed-globally package is then useful if you want to generate relative paths to the distributed files depending if they are installed locally or globally: How to tell if npm package was installed globally or locally