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
。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2022-03-07 form表单中name和id的区别