node.js如何引用外部js

2023-06-25

这篇文章给大家分享的是有关node.js如何引用外部js的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

基本语句

require('js文件路径');

使用方法

举个例子,在同一个目录下,有fun、fun1、fun2三个js文件。

fun.js

var fun1 = require('./fun1');
var fun2 = require('./fun2');

function test(){
     console.log("调用了fun的test方法");
     fun1.add(1,2);
     fun2();
}
     test();

fun1.js

function reduce(a,b){
    console.log("调用了fun1的reduce方法");
    console.log(a-b);
}

function add(a,b){
    console.log("调用了fun1的add方法");
    console.log(a+b);
}
module.exports = {
 reduce,
 add
}

fun2.js

module.exports = function  print(){
    console.log("调用了fun2的print方法");
}
这种的调用方法为: fun2();
或者

module.exports = {
    print:function(){
        console.log("调用了fun2的print方法");
    },
    copy:function(a,b){
          console.log("我是fun2的copy方法");
    }
}

这种的调用方法为:fun2.print();

可以看到fun1和fun2的写法略有不同,fun1这种写法更好,因为它可以只把别的文件需要调用的函数导出,未导出的函数别的js文件是用不了的

输出结果如下:

调用了app的test方法
调用了fun1的add方法
3
调用了fun2的print方法

感谢各位的阅读!关于node.js如何引用外部js就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

《node.js如何引用外部js.doc》

下载本文的Word格式文档,以方便收藏与打印。