Are all packages also modules in Node? - node.js

I've read npm doc, but still couple of my concepts are still unclear which may seem naive, are as follows:
Q1.
A package is a file or directory that is described by a package.json
file.
What do they meant by "described by a package.json file"? Any example to understand easily?
Q2.
Condition to be a package
A package is a file or directory that is described by a package.json
file.
Condition to be a module
To be loaded by the Node.js require() function, a module must be one
of the following:
A folder with a package.json file containing a "main" field.
A folder with an index.js file in it.
A JavaScript file.
Note: Since modules are not required to have a package.json file, not
all modules are packages. Only modules that have a package.json file
are also packages.
So, as per the Note, shouldn't it also implies that all packages are also modules as all packages have package.json files?

A module is anything that can be loaded with require() and does something useful. It can be a single file. It does not need to have a package.json associated with it. In fact, many locally developed "modules" do not. You can have many modules in the same directory.
A package is a set of code designed for easy distribution. If you are using the NPM package manager, then an NPM package will contain a package.json file that has a bunch of meta data about the package, including things like dependencies on other modules, author info, repository info, info on how to test the module, info on which file is the startup file for the module, etc...
FYI, NPM is not the only package manager so it's not the only way of doing things, but for node.js development it is certainly the most widely used and it offers a central repository that makes it easy the "publish" packages for wide and simple distribution.
Are all packages also modules in Node?
I suppose it's possible to distribute something other than runnable code in a package, but the primary use of an NPM package is to distribute modules.
Here's an example of destributing static data rather than code: JSON Data Node Modules Part 1: Using NPM to Store and Distribute Static Data.

Related

Should core Node modules be listed in package.json

My code uses core Node modules such as fs and path. Is there any reason to include them in package.json (npm i fs path)? The README for npm path says "This is an exact copy of the NodeJS ’path’ module published to the NPM registry." Why do these packages have around a million downloads a week?
Is there any reason to include them in package.json (npm i fs path)?
No. These packages have been bundled as part of every major Node release since its inception. They do not need to be installed separately or included in your package.json file.
Why do these packages have around a million downloads a week?
I suppose you could really only speculate, but it's likely that a nonzero number of newcomers aren't aware these modules are available as part of the core of Node and are running npm install fs, etc. following the same idea as some of the documentation or tutorials they're reviewing.
It's prudent to ensure that not only if one does include these modules that they work as intended, but to also prevent unscrupulous actors from namesquatting and enabling dependency confusion vulnerabilities. The npm page for the fs module even states explicitly why they've elected to publish it (emphasis mine):
This package name is not currently in use, but was formerly occupied by another package. To avoid malicious use, npm is hanging on to the package name, but loosely, and we'll probably give it to you if you want it.
As mentioned in similar question, you don't need install it, so you don't need specify it in package.json. Also fs, path are Node.js core modules.
Sorry for my bad english. Have a nice day!

Build strategies for utilizing npm packages

This must be a commonly solved problem, but I cannot find a whole lot on Google/SO so far.
When we run npm install and fetch say 50+ packages including devDependencies as well as runtime dependencies, npm creates node_modules (if needed) and adds each of those packages inside that folder. This means we end up with thousands of extraneous files included under node_modules. Each of those packages contains their own package.json, README.md, minified files, source files, etc. Our application really only cares about jquery.js (for DEV) and jquery.min.js (for PROD), so it seems to be a waste to include all of these other files into our build and therefore our web server.
Is there a standard when it comes to handle these npm packages in a way so that we simply expose ONLY the necessary files to the user? I imagine many people have this kind of issue but I don't see any built in npm constructs that allow us to do this easily.
See below.. the yellow highlighted files are the only files we really care about in Production, but we get all these extra files as well including the source code.
The most common solution consist of bundling your application on a different machine and then expose the built artefacts on production server.
There are a lot of great JS bundlers out there. The ones I have personally used are Browserify, Webpack, and Rollup. All amazing tools.
The main idea consists of writing your application in a Node environment and then bundle it to make it readable to the browser.
For simpler projects I find Browserify a very good compromise between power and ease of configuration. But it's a matter of taste, at the end. :)
Base on what I read about npm install documentation I do not think there is a option to manipulate the installation in the way you want. The packages will install the way the package author decides to package it, sometimes minified sometimes not.
Having said that, you should look for third party solutions like modclean which does exactly what you want post package installation. Run this command in the root of your project directory
npm install modclean -g
modclean
As long as your test coverage is good, ModClean would be perfect for your need.
Edit the package.json file and remove all the unnecessary dependencies then do
npm install --save
By doing this, it will create a local node_modules folder and only download the necessary packages into it (not the global node_modules folder)
Keep in mind, by default, node checks for local node_modules folder. If it couldn't find it, it will use the global folder.
Also, you don't expose all the packages in the node_modules folder. In fact, they will not be used unless you require(); them in the node.js file
EDIT:
For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as jsdom. This can be useful for testing purposes. https://www.npmjs.com/package/jquery
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
So jquery module do things a bit differently behind the scene for node.js comparing to the regular front-end jquery.
It requires jsdom so you will have to download that as well from here https://github.com/tmpvar/jsdom

Can I create an npm package that sets up another npm package?

I want to create an npm package that would be installed globally, with a binary to call. Calling that binary would set up the initial files for a new project, like your standard folders, standard license and layouts, a package.json with your common dependencies. Then you could call npm install to actually set up that project.
Like the Express application generator, or like rails new does in Ruby. The usage would be like
mkdir new_project
cd new_project
myCoolGenerator new
npm install
But I'm confused about how I'd implement this. The simple approach, which I'm doing now, is to create the standard vanilla folder, ship it with the generator package, and then just have the main binary use ncp to copy that folder into wherever the caller currently is.
My problem there is that I don't know how I can access the folder included in the globally-installed package to copy over. And additionally, npm lets you specify a files array in your package.json to specify files included with the package, but it's apparently hardwired to ignore package.json from that.
What's the recommended procedure for this sort of thing?

Efficiently Bundling Dependencies with Electron App for Distribution

I am trying to figure out an effective way to bundle and distribute various dependencies (node modules and/or "client"-side scripts and framework like Angular) with my Electron App.
Although the basic approach of npm install module-name --save works well for development, it is not so good in the end when it comes to minimizing the size of your app and using minified resources at runtime. For instance, virtually all npm packages (including node modules) come with a lot of "extra baggage" like readmes, various versions of components (minified, not minified, ES2015, no-ES2015, etc). While these are great for development, all these files have absolutely no need to be included in the version you will be distributing.
Currently there seem to be 2 ways to sort of address the problem:
Electron Builder recommends using 2-file package.json system.
Any dependency that is used during development only should be npm-installed using --save-dev and then prunning should be used when building the app for distribution.
In that regard I have several questions:
I am not quite sure why there is a need for 2-file package.json system if one can install dev-only modules/ dependencies with --save-dev and then use pruning during the actual app build/compilation?
Regardless of which method above is used, you still end up with full npm packages in your app, inclduying all the miscellaneous/duplicated files that are not used by your app. So how does one "prune" so to speak the npm packages themselves so that only the actual files that are being used at run-time (like minified scripts) get included?
Will using Bower for "client-side" packages (like AngularJS 2, Bootstrap, jQuery, etc.) and using npm for node modules (like fs-extra) be a better option in as far as separation of concerns and ease of bundling later?
Could WebPack be used to produce only the needed files, at least for the "cient-side", so that only real node modules will be included with the app, while the rest of it will be in the form of web-pack compiled set of files?
Any practical tips on how this bundling of dependencies and distribution should be accredited out in practice? Gulp-scripts? Web-pack scripts? Project structure?
Thank you.
I am still in the learning curve of adopting the best practices in code deployment. But here is my starting list of what is recommended.
Yes, npm install --save-dev is the first easiest thing to isolate dev and build specific packages. This includes gulp/grunt/webpack and its loaders or additional packages. These are used only for building and never in the code that actually is run. All packages used by the app should be installed with npm install --save so that it is project level available. So, in production, you would no npm install --production in machines which will not install dev packages at all. See What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file? for more info.
While the original recommendation was to use bower for client side and npm for server side, both can be installed using npm too. After all, both does the same job of managing the packages and dependencies. However, if web pack is used, it is recommended that npm is used for client side dependencies also.
package.json should be thought of managing the dependent packages only and not for building. For building and picking only the required files, you need task runners like gulp/grunt or bundlers like web pack.
While gulp/grunt is very popular for build automation which includes bundling all dependent javascript in file and minifying them in to one file, webpack/browserify is a better option as it supports module import. Module import is intuitive way of require one module in another in node js type of coding
var util = require('./myapp/lib/utils.js') This is powerful way of mentioning the required dependencies in the code. The web pack builder runs like gulp as build process. But instead of looking through html file for all js files, looks at starting js file and and determines all dependent code mentioned by the require statements recursively and packages accordingly. It also minifies the code. It also loads css and image files in one bundle to reduce server trips. If needed, some modules can be configured to be loaded at runtime dynamically further reducing page load. NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack discusses this at length.
Webpack can be used to bundle client side app optimally while server side need not be bundled or minified as there is no download.
In web pack, though you can mention dependent modules with lib file path, the recommendation is to npm install all dependencies and mention the module name. For example if you have installed jquery, instead of giving path like /libs/jquery.min.js, you can mention as 'jquery'. Webpack will automatically pull the jquery lib and dependencies and minimise it. If they are common modules, it will be chunked too. So, it is better to npm install dependent packages instead of bower install.
ES2015 provides lot of benefits during coding time including type checking and modules. However all browsers do not yet support the spec natively. So you need to transpile the code to older version that browsers understand. This is done by transpilers like Babel that can be run with gulp. Webpack has in-built babel loader so web pack understands ES2015. It is recommended to use ES2015 module system as it will soon become the defacto way of coding and since there is transpiler, there is no worry of this not being supported in IE8/9.
For project structure you could have
server
client
src containing js files
dist containing html and build files generated
webpack.dev.config.js and webpack.prod.config.js can be at root level.
I have found that this area is an ocean and different schools of best practices.This is probably one set of best practices. Feel free to choose the set that works for your scenario. Look forward for more comments to add to this set.

Download node module sources without installing them?

I would like to download node module packages (listed in a package.json file, in the present working directory) source code to a node_modules subdirectory of the present working directory, without compiling, or installing those modules. Now I have seen the related question download source from npm without npm install xxx but that question dealt with downloading the source code of individual modules specified to NPM directly (i.e., without using a package.json file). The reason why I want to do this is because I am working on developing an Atom package for the Open Build Service (OBS) of openSUSE and this seems like one of the necessary steps I need to go through in order to achieve this.
The source code is not shipped with the npm distributed code. The best you could do is read the package.json and look for the { repository: url { } } key if it exists and if it's a git repo (which most of them will be) clone it.
However be aware that the source code often requires a build step before it can be used, as in an npm prepublish step defined in the source code. In modern Javascript projects a common example of this is transpiling ES6 code to ES5 code for use in NodeJS and the browser.
I have not made an Atom package but I'm fairly certain you don't need to do any of this.

Resources