node.js如何引用其它js文件

以Java来讲,好比要实现第三方存储,我可能须要导入对应的库,以maven为例,使用腾讯云或者七牛云、阿里云,我须要导入对应的maven依赖。
再好比,有些时候咱们封装某个类,而那个类不在该包下,咱们须要导包(就是指定那个类的路径,若是路径不对,则可能出现找不到这个类之类的错误,一般对应的IDE会提示错误)。html

其实,node.js也是这样的。最近在开发node.js的时候,不免也会遇到须要引入其它js文件。今天我以一个简单示例来讲一说node.js如何引用其它js文件。node

test01.jsnpm

function hello(){
    
    console.log("hello");
}

function hello2(){
    
    console.log("hello2");
}

module.exports = {hello,hello2}

test02.jsmaven

var test01 = require( "./test01" );

test01.hello();

test01.hello2();

经过命令行运行node test02.js 正常会分别输出hello、hello2。ui

require是什么意思呢?
其实就跟咱们Java开发导包同样的意思,在Java中是import,其实node.js也能够import式导包。阿里云

那么node.js中的require和import导包有什么区别呢?
(1)require导包位置任意,而import导包必须在文件的最开始;
(2)遵循的规范不一样,require/exports是CommonJS的一部分,而import/export是ES6的规范;
(3)出现时间不一样,CommonJS做为node.js的规范,一直沿用至今,主要是由于npm善CommonJS的类库众多,以及CommonJS和ES6之间的差别,Node.js没法直接兼容ES6。因此现阶段require/exports仍然是必要且必须的;
(4)形式不一样,require/exports的用法只有如下三种简单写法:spa

const fs = require('fs');
— — — — — — — — — — — — — — 
exports.fs = fs;
module.exports = fs;

而import/exports的写法就多种多样命令行

import fs from 'fs';
import {default as fs} from 'fs';
import * as fs from 'fs';
import {readFile} from 'fs';
import {readFile as read} from 'fs';
import fs, {readFile} from 'fs';
— — — — — — — — — — — — — — — — — — — — 
export default fs;
export const fs;
export function readFile;
export {readFile, read};
export * from 'fs';

(5)本质上不一样,主要体现:
a.CommonJS仍是ES6 Module 输出均可以当作是一个具有多个属性或者方法的对象;
b.default是ES6 Module所独有的关键字,export default fs 输出默认的接口对象,import fs from ‘fs’可直接导入这个对象;
c.ES6 Module 中导入模块的属性或者方法是强绑定的,包括基础类型,而CommonJS则普通的值传递或者引用传递;code

本文参考连接以下所示:
node.js如何引用其它js文件:http://www.javashuo.com/article/p-deqylwbp-hn.html
关于require/import的区别:https://www.jianshu.com/p/fd39e16feb60htm

相关文章
相关标签/搜索