Root directory in package.json

前端 未结 7 1663
臣服心动
臣服心动 2020-12-25 10:25

My question concerns an existing library that I wish to publish as an NPM module. The library is already in use, and currently required via the local file syste

7条回答
  •  独厮守ぢ
    2020-12-25 11:20

    Simply publish /install /link the folder intended to be the root

    The natural way to achieve that, according to the npm approach, is to publish the folder which is to be the root. There are several ways to do that, depends on the final environment you want to work with:

    1. npm publish from your package repo to an npm registry and then install your package in other project as you install other packages. In your case it would be npm publish src/js/lib/my.
    2. npm install in some other project if you want to use your package only locally. In your case you go to the other project and run npm install relative/path/to/src/js/lib/my
    3. npm link your folder locally to node_modules in other project in case you'd like to have the changes in your original package reflected instantly in other project. In your case you first cd src/js/lib/my and run npm link and then go to the other project and run npm link my.

    Prerequisite: in any case above, prior to the publish/install/link, you have to put in your my folder at least a proper package.json file. In your case, you have to have the package name defined in the package.json file as "name": "my". Typically you'll want there also some other files like README.md or LICENSE.

    Automation example

    You can automate the publishing process using the prepare script, combined with build script and "private": true field put in the package.json located in the root directory of your package repo. Here is an example with the dist folder as a package root:

      "private": true,
      "scripts": {
        "build": "rm -rf dist && webpack --mode=production && cat ./package.json | grep -v '\"private\":' > dist/package.json",
        "prepare": "npm run build"
      },
    

    This way you won't publish the root folder ("private": true). And when you hit npm publish dist the automatically invoked prepare script will trigger dist folder cleanup (rm -rf dist), package build (webpack --mode=production) and copy of the package.jsonto the dist folder without the field "private": true (cat ./package.json | grep -v private > dist/package.json).

提交回复
热议问题