Reputation: 364
I am creating a custom npm package and i would like to add a JSON config file.
I would like to add this file in the root path of the node app when a npm install mypackage
is done
I know it is possible as this is what typescript is doing, adding a tsconfig.json file in my app folder when I do npm install typescript
I guess it is a package.json config but I don't know which.
Thanks
Upvotes: 0
Views: 589
Reputation: 364
I solved this using genechk awnser :
I had to add a "postinstall" script to my package.json, but i also had to add "node" command before in order to execute the script :
"scripts" : [
...
"postinstall" : "node scripts/postinstall.js"
]
Also i had to add the script to the delivered files from the package :
"files": [
...
"scripts/**/*"
]
Finlay my postinstall.js looks like this :
const fs = require('fs');
// __dirname is "{ProjectFolder}/node_modules/mypackage/config"
const CONFIG_SRC = `${__dirname}/../config/`;
const CONFIG_DEST = `${__dirname}/../../../`;
const CONFIG_MYPACKAGE = 'mypackageconfig.json';
fs.copyFile(`${CONFIG_SRC}/${CONFIG_MYPACKAGE}`, `${CONFIG_DEST}/${CONFIG_MYPACKAGE}`, (err) => {
if (err) throw err;
console.log(`File ${CONFIG_MYPACKAGE} copied`);
});
Also to be fully proper i had to use an uninstall.js script following the same logic and deleting the file
Upvotes: 0
Reputation: 389
You can achieve this using postinstall
script.
{ "scripts" :
...
"postinstall" : "scripts/postinstall.js"
}
}
Here’s the explanation of npm lifecycle events in docs:
For example, if your package.json contains this:
{ "scripts" : { "install" : "scripts/install.js" , "postinstall" : "scripts/install.js" , "uninstall" : "scripts/uninstall.js" } }
then scripts/install.js will be called for the install and post-install stages of the lifecycle, and scripts/uninstall.js will be called when the package is uninstalled. Since scripts/install.js is running for two different phases, it would be wise in this case to look at the npm_lifecycle_event environment variable.
Upvotes: 1