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

posted @   KongLong_cm  阅读(1164)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-03-07 form表单中name和id的区别
点击右上角即可分享
微信分享提示