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 @ 2024-03-07 09:50  KongLong_cm  阅读(554)  评论(0编辑  收藏  举报