How to publish a npm package with distribution files?

后端 未结 3 930
挽巷
挽巷 2020-12-02 07:32

I would like to publish a npm package that contains my source as well as distribution files. My Github repository contains src folder which contains JavaScript

3条回答
  •  半阙折子戏
    2020-12-02 08:19

    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:

    • source: https://github.com/cirosantilli/linux-kernel-module-cheat/tree/008bd8000234d74e00845939ea6c47d302a26706/npm/data-files
    • published: https://www.npmjs.com/package/cirosantilli-data-files

    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 node
    const 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

提交回复
热议问题