I just discovered that the require module will also affect subsequent require, taking moment and moment-timezone as examples, that is to say:
/app.js
var moment = require('moment');
console.log(moment.tz());
// 这样会报错,因为moment.tz()是moment-timezone这个module才有的function
/*
TypeError: moment.tz is not a function
*/
But if I require moment-timezone first, and then require moment, npm install moment, I can still require('moment') and this moment can use the function of moment-timezone, as follows
/app.js
require('moment-timezone')
var moment = require('moment');
console.log(moment.tz()); //moment.utc("2017-06-27T06:59:14.475+00:00")
What I don't understand is why after require('moment-timezone'), even if I don't have npm install moment, I can still require('moment'); without reporting an error?
What is the design of such node modules or is there any special term that can cause such behavior?
By the way, if the above moment-timezone can be designed like this, suppose I released a module called noname for people to use on npm today. As long as the program executes require('noname'); first, is it possible? Changed the return content of the subsequent require('express') module to achieve a similar effect to the following:
require('noname');
var express = require('express');
express.thisIsMyExpress();//这是被我换过的express module
1. Why after
require('moment-timezone')
, even if I don'tnpm install moment
I can stillrequire('moment')
without getting an error?View
moment-timezone
DependenciesIt can be seen that
moment-timezone
is dependent onmoment
, which means thatmoment
will be automatically installed when installingmoment-timezone
, so it can be used without installing it separately.2. Why does
require('moment-timezone')
affect the subsequent assignment of `moment` invar moment = require('moment')
View
moment-timezone
source codeOn line 14, you can see that
moment-timezone
has modifiedrequire('moment')
. As we all know, thenpm
module will be cached, so the subsequentvar moment = require('moment')
will be affectedBy the way, directly modifying modules is the same as modifying global variables, which is not a good practice. The
moment-timezone
module here is basically a patch of the `moment` module and is a special case.