Can I force Node.JS install npm-package when executing require('package')
instead of triggering error?
It will be more convenient than running npm i package for every package.
Dependency packages should be managed through package.json file. It's because you can easily manage the version of packages required by you application. I don't think it's a good practice to install dependency at runtime.
Reference: Using a package.json
You can't set Node.js to do this (since Node doesn't actually know about npm).
I wouldn't recommend doing anything like this; if you mistyped a package name, you would download the wrong package, possibly running malicious code on your computer.
Remember, anyone can publish an npm package, and packages can run any command (including rm -rf) during the installation process.
Follow the below at your own risk:
You can get something like the behavior you're describing with https://github.com/siddharthkp/auto-install.
npm install -g auto-install
cd project-name/
auto-install
I would recommend using the --secure option for auto-install. That will only install popular modules (> 10k downloads in the last month). This will eliminate some of the risk of typos, however, if you're using an uncommon package, it won't be installed automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With