Js引用其他Js文件中的方法(nodejs环境)
目前已知有两种方法,例如在A.js
文件中引用B.js
文件中的方法。
先说第一种:
B.js
文件是这样的,
function hello(){
console.log("Hello world");
}
exports.hello = h;
那么在A.js
文件中可以这样引用,
// var hello = require('./B.js');
const hello = require('./B.js');
hello.h()
下面说第二种:
B.js
文件这样写,
function hello(){
console.log("Hello world");
}
module.exports = {hello};
在A.js
文件中就可以这样引用,
// var hello = require('./B.js');
const hello = require('./B.js');
hello()
但不管是哪一种方式,都要在被引用文件中加上类似exports
这样,不加上的话会报错有问题。
注意:如果被引用的方法中还嵌套声明了其他方法,例如:
module.exports=function hello(){
function a(){
console.log("hhh,");
}
console.log("Hello world");
}
暴露该方法时要在方法头前面加上module.exports=
,如果还是像前两个那样写执行时就会报错:TypeError: hello is not a function
。