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:
- npm publish <folder> 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
.
- npm install <folder> 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
- 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.
Remarks to methods 2 & 3
Typically there are problems with package dependencies when you use the package installed this way. To avoid it, first pack the package with npm pack dist
and then install the package in the target project from the packed tarball, i.e. npm install path/to/package-tarball.tgz
.
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
).